using System.Text.Json; using Microsoft.Extensions.Caching.Memory; namespace MesaFabApproval.Client.Services; public interface ICustomerService { Task> GetAllCustomerNames(); } public class CustomerService : ICustomerService { private readonly IMemoryCache _cache; private readonly IHttpClientFactory _httpClientFactory; public CustomerService(IMemoryCache cache, IHttpClientFactory httpClientFactory) { _cache = cache ?? throw new ArgumentNullException("IMemoryCache not injected"); _httpClientFactory = httpClientFactory ?? throw new ArgumentNullException("IHttpClientFactory not injected"); } public async Task> GetAllCustomerNames() { IEnumerable? allCustomerNames = null; allCustomerNames = _cache.Get>("allCustomerNames"); if (allCustomerNames is null) { HttpClient httpClient = _httpClientFactory.CreateClient("API"); HttpRequestMessage requestMessage = new(HttpMethod.Get, $"customer/all"); HttpResponseMessage responseMessage = await httpClient.SendAsync(requestMessage); if (responseMessage.IsSuccessStatusCode) { string responseContent = await responseMessage.Content.ReadAsStringAsync(); JsonSerializerOptions jsonSerializerOptions = new() { PropertyNameCaseInsensitive = true }; allCustomerNames = JsonSerializer.Deserialize>(responseContent, jsonSerializerOptions) ?? throw new Exception("Unable to parse names from API response"); _cache.Set($"allCustomerNames", allCustomerNames, DateTimeOffset.Now.AddHours(1)); } else { throw new Exception($"Unable to get all customer names, because {responseMessage.ReasonPhrase}"); } } return allCustomerNames; } }