2024-11-15 09:28:21 -07:00

52 lines
1.9 KiB
C#

using System.Text.Json;
using Microsoft.Extensions.Caching.Memory;
namespace MesaFabApproval.Client.Services;
public interface ICustomerService {
Task<IEnumerable<string>> 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<IEnumerable<string>> GetAllCustomerNames() {
IEnumerable<string>? allCustomerNames = null;
allCustomerNames = _cache.Get<IEnumerable<string>>("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<IEnumerable<string>>(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;
}
}