namespace AAIntegration.SimmonsBank.API.Services; using AAIntegration.SimmonsBank.API.Config; using AAIntegration.SimmonsBank.API.Entities; using Microsoft.Extensions.Caching.Memory; public interface ICacheService { int GetClientIdFromApiKey(string apiKey); T GetCachedUserValue(User user, string cacheKey, T fallback); void SetCachedUserValue(User user, string cacheKey, T value); } public class CacheService : ICacheService { private DataContext _context; private readonly IMemoryCache _memoryCache; private readonly ILogger _logger; public CacheService( DataContext context, IMemoryCache memoryCache, ILogger logger) { _context = context; _memoryCache = memoryCache; _logger = logger; } public int GetClientIdFromApiKey(string apiKey) { if (!_memoryCache.TryGetValue>($"Authentication_ApiKeys", out var internalKeys)) { _logger.LogInformation($"Could not find API key '{apiKey}' in cache."); internalKeys = _context.Users .Where(u => u.ApiKey != null) .ToDictionary(u => u.ApiKey, u => u.Id); _logger.LogInformation("Updated cache with new key list."); PrintInternalKeys(internalKeys); _memoryCache.Set($"Authentication_ApiKeys", internalKeys); } if (!internalKeys.TryGetValue(apiKey, out var clientId)) { _logger.LogInformation("Could not find API key. Returning -1."); return -1; } return clientId; } public T GetCachedUserValue(User user, string cacheKey, T fallback) { if (_memoryCache.TryGetValue>(cacheKey, out var internalKeys)) { internalKeys ??= new Dictionary(); List> list = internalKeys.Where(x => x.Key == user.Id).ToList(); if (list.Count > 0 && list.First().Value != null) { _logger.LogInformation($"Found the '{typeof(T)}' type cached for user with id '{user.Id}' in cache '{cacheKey}'."); return list.First().Value; } } return fallback; } public void SetCachedUserValue(User user, string cacheKey, T value) { _memoryCache.TryGetValue>(cacheKey, out var internalKeys); internalKeys ??= new Dictionary(); if (internalKeys.ContainsKey(user.Id)) internalKeys[user.Id] = value; else internalKeys.Add(user.Id, value); _memoryCache.Set(cacheKey, internalKeys); } // helpers private void PrintInternalKeys(Dictionary keys) { string msg = "API Keys (dev only - needs to be moved to dev only)"; foreach (var item in keys) msg += $"\n\t{item.Value} : {item.Key}"; _logger.LogInformation(msg); } /*public void InvalidateApiKey(string apiKey) { if (_memoryCache.TryGetValue>("Authentication_ApiKeys", out var internalKeys)) { if (internalKeys.ContainsKey(apiKey)) { internalKeys.Remove(apiKey); _memoryCache.Set("Authentication_ApiKeys", internalKeys); } } _userService.InvalidateApiKey(apiKey); }*/ }