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:
Janus C. H. Knudsen 2026-01-25 17:05:24 +01:00
parent 1b25978d9b
commit 33804d002e

View file

@ -6,6 +6,7 @@ namespace PlanTempus.Application.Features.Localization.Services;
public class JsonLocalizationService : ILocalizationService
{
private readonly string _translationsPath;
private readonly Dictionary<string, JsonDocument> _cache = new();
public JsonLocalizationService(IWebHostEnvironment env)
{
@ -17,14 +18,11 @@ public class JsonLocalizationService : ILocalizationService
public string Get(string key, string? culture = null)
{
culture ??= CurrentCulture;
var filePath = Path.Combine(_translationsPath, $"{culture}.json");
var doc = GetDocument(culture);
if (!File.Exists(filePath))
if (doc == null)
return key;
var json = File.ReadAllText(filePath);
var doc = JsonDocument.Parse(json);
var parts = key.Split('.');
JsonElement current = doc.RootElement;
@ -35,6 +33,23 @@ public class JsonLocalizationService : ILocalizationService
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()
{
return new List<SupportedCulture>