diff --git a/EnvelopeGenerator.Application/Extensions/CacheExtensions.cs b/EnvelopeGenerator.Application/Extensions/CacheExtensions.cs index f2adcebd..5e9eebd8 100644 --- a/EnvelopeGenerator.Application/Extensions/CacheExtensions.cs +++ b/EnvelopeGenerator.Application/Extensions/CacheExtensions.cs @@ -33,6 +33,10 @@ namespace EnvelopeGenerator.Application.Extensions return value is null ? null : new(BitConverter.ToInt64(value, 0)); } + //TODO: use code generator + #region GetOrSetAsync + + #region string public static async Task GetOrSetAsync(this IDistributedCache cache, string key, Func factory, DistributedCacheEntryOptions? options = null, bool cacheInBackground = false, CancellationToken cToken = default) { var value = await cache.GetStringAsync(key, cToken); @@ -74,5 +78,54 @@ namespace EnvelopeGenerator.Application.Extensions return value; } + #endregion + + #region DateTime + public static async Task GetOrSetAsync(this IDistributedCache cache, string key, Func factory, DistributedCacheEntryOptions? options = null, bool cacheInBackground = false, CancellationToken cToken = default) + { + if (await cache.GetDateTimeAsync(key, cToken) is DateTime dateTimeValue) + return dateTimeValue; + else + { + // create new and save + var newValue = factory(); + + Task CacheAsync() => options is null + ? cache.SetDateTimeAsync(key, newValue, cToken: cToken) + : cache.SetDateTimeAsync(key, newValue, options, cToken); + + if (cacheInBackground) + _ = Task.Run(async () => await CacheAsync(), cToken); + else + await CacheAsync(); + + return newValue; + } + } + + public static async Task GetOrSetAsync(this IDistributedCache cache, string key, Func> factory, DistributedCacheEntryOptions? options = null, bool cacheInBackground = false, CancellationToken cToken = default) + { + if (await cache.GetDateTimeAsync(key, cToken) is DateTime dateTimeValue) + return dateTimeValue; + else + { + // create new and save + var newValue = await factory(); + + Task CacheAsync() => options is null + ? cache.SetDateTimeAsync(key, newValue, cToken: cToken) + : cache.SetDateTimeAsync(key, newValue, options, cToken); + + if (cacheInBackground) + _ = Task.Run(async () => await CacheAsync(), cToken); + else + await CacheAsync(); + + return newValue; + } + } + #endregion + + #endregion } } \ No newline at end of file