From 234d7163fc6498ab8b263d0aacd9176009cc6468 Mon Sep 17 00:00:00 2001 From: "DESKTOP-GENO133\\IvanPlex" Date: Sat, 3 Feb 2024 11:01:54 -0700 Subject: [PATCH] added caching to reduce number of IO reads. --- Helper/TranslationHelper.cs | 39 ++++++++++++++++++++++++------------- 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/Helper/TranslationHelper.cs b/Helper/TranslationHelper.cs index 0933fb3..e454396 100644 --- a/Helper/TranslationHelper.cs +++ b/Helper/TranslationHelper.cs @@ -1,4 +1,5 @@ using CarCareTracker.Models; +using Microsoft.Extensions.Caching.Memory; using System.Text.Json; namespace CarCareTracker.Helper @@ -11,10 +12,12 @@ namespace CarCareTracker.Helper { private readonly IFileHelper _fileHelper; private readonly IConfiguration _config; - public TranslationHelper(IFileHelper fileHelper, IConfiguration config) + private IMemoryCache _cache; + public TranslationHelper(IFileHelper fileHelper, IConfiguration config, IMemoryCache memoryCache) { _fileHelper = fileHelper; _config = config; + _cache = memoryCache; } public string Translate(string userLanguage, string text) { @@ -22,22 +25,32 @@ namespace CarCareTracker.Helper //transform input text into key. string translationKey = text.Replace(" ", "_"); var translationFilePath = _fileHelper.GetFullFilePath($"/translations/{userLanguage}.json", false); - if (File.Exists(translationFilePath)) + var dictionary = _cache.GetOrCreate>($"lang_{userLanguage}", entry => { - var translationFile = File.ReadAllText(translationFilePath); - var translationDictionary = JsonSerializer.Deserialize>(translationFile); - if (translationDictionary != null && translationDictionary.ContainsKey(translationKey)) + entry.SlidingExpiration = TimeSpan.FromHours(1); + if (File.Exists(translationFilePath)) { - return translationDictionary[translationKey]; - } else if (create) - { - //create entry - translationDictionary.Add(translationKey, text); - File.WriteAllText(translationFilePath, JsonSerializer.Serialize(translationDictionary)); - return text; + var translationFile = File.ReadAllText(translationFilePath); + var translationDictionary = JsonSerializer.Deserialize>(translationFile); + return translationDictionary ?? new Dictionary(); } + else + { + return new Dictionary(); + } + }); + if (dictionary != null && dictionary.ContainsKey(translationKey)) + { + return dictionary[translationKey]; } - return create ? string.Empty : text; + else if (create && File.Exists(translationFilePath)) + { + //create entry + dictionary.Add(translationKey, text); + File.WriteAllText(translationFilePath, JsonSerializer.Serialize(dictionary)); + return text; + } + return text; } } }