You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Connected.Common/Common/Globalization/LanguageCache.cs

78 lines
1.8 KiB

2 years ago
using System.Collections.Immutable;
using Connected.Entities.Caching;
using Connected.ServiceModel;
namespace Common.Globalization;
internal interface ILanguageCache : IEntityCacheClient<Language, int>
{
Language? Select(string mappings);
}
/// <summary>
/// Represents stateful cache of the <see cref="Language"/> entities.
/// </summary>
internal class LanguageCache : EntityCacheClient<Language, int>, ILanguageCache
{
private readonly Dictionary<string, Language> _mappings;
public LanguageCache(IEntityCacheContext context) : base(context, Language.CacheKey)
{
_mappings = new Dictionary<string, Language>(StringComparer.OrdinalIgnoreCase);
}
private Dictionary<string, Language> Mappings => _mappings;
protected override async Task<ImmutableList<Language>> OnInitializing(IContext context)
{
var result = await base.OnInitializing(context);
await ResetMappings();
return result;
}
protected override async Task<Language> OnInvalidating(IContext context, int id)
{
var result = await base.OnInvalidating(context, id);
await ResetMappings();
return result;
}
public Language? Select(string mappings)
{
if (string.IsNullOrWhiteSpace(mappings))
return null;
var tokens = mappings.Split(',', StringSplitOptions.RemoveEmptyEntries);
foreach (var token in tokens)
{
if (Mappings.TryGetValue(token.Trim(), out Language? language))
return language;
}
return null;
}
private async Task ResetMappings()
{
Mappings.Clear();
foreach (var language in await All())
{
if (string.IsNullOrWhiteSpace(language.Mappings))
continue;
var tokens = language.Mappings.Split(',', StringSplitOptions.RemoveEmptyEntries);
foreach (var token in tokens)
{
if (Mappings.TryGetValue(token.Trim(), out _))
continue;
Mappings.Add(token.Trim(), language);
}
}
}
}