Adds caching to JSON localization service
Introduces a caching mechanism for localization JSON documents to improve performance Prevents repeated file reads by storing parsed JSON documents in memory Adds GetDocument method to manage document retrieval and caching Reduces file system I/O overhead for localization translations
This commit is contained in:
parent
1b25978d9b
commit
33804d002e
1 changed files with 20 additions and 5 deletions
|
|
@ -6,6 +6,7 @@ namespace PlanTempus.Application.Features.Localization.Services;
|
||||||
public class JsonLocalizationService : ILocalizationService
|
public class JsonLocalizationService : ILocalizationService
|
||||||
{
|
{
|
||||||
private readonly string _translationsPath;
|
private readonly string _translationsPath;
|
||||||
|
private readonly Dictionary<string, JsonDocument> _cache = new();
|
||||||
|
|
||||||
public JsonLocalizationService(IWebHostEnvironment env)
|
public JsonLocalizationService(IWebHostEnvironment env)
|
||||||
{
|
{
|
||||||
|
|
@ -17,14 +18,11 @@ public class JsonLocalizationService : ILocalizationService
|
||||||
public string Get(string key, string? culture = null)
|
public string Get(string key, string? culture = null)
|
||||||
{
|
{
|
||||||
culture ??= CurrentCulture;
|
culture ??= CurrentCulture;
|
||||||
var filePath = Path.Combine(_translationsPath, $"{culture}.json");
|
var doc = GetDocument(culture);
|
||||||
|
|
||||||
if (!File.Exists(filePath))
|
if (doc == null)
|
||||||
return key;
|
return key;
|
||||||
|
|
||||||
var json = File.ReadAllText(filePath);
|
|
||||||
var doc = JsonDocument.Parse(json);
|
|
||||||
|
|
||||||
var parts = key.Split('.');
|
var parts = key.Split('.');
|
||||||
JsonElement current = doc.RootElement;
|
JsonElement current = doc.RootElement;
|
||||||
|
|
||||||
|
|
@ -35,6 +33,23 @@ public class JsonLocalizationService : ILocalizationService
|
||||||
return current.GetString() ?? key;
|
return current.GetString() ?? key;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private JsonDocument? GetDocument(string culture)
|
||||||
|
{
|
||||||
|
if (_cache.TryGetValue(culture, out var cached))
|
||||||
|
return cached;
|
||||||
|
|
||||||
|
var filePath = Path.Combine(_translationsPath, $"{culture}.json");
|
||||||
|
|
||||||
|
if (!File.Exists(filePath))
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var json = File.ReadAllText(filePath);
|
||||||
|
var doc = JsonDocument.Parse(json);
|
||||||
|
_cache[culture] = doc;
|
||||||
|
|
||||||
|
return doc;
|
||||||
|
}
|
||||||
|
|
||||||
public IEnumerable<SupportedCulture> GetSupportedCultures()
|
public IEnumerable<SupportedCulture> GetSupportedCultures()
|
||||||
{
|
{
|
||||||
return new List<SupportedCulture>
|
return new List<SupportedCulture>
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue