MRB webassembly
This commit is contained in:
51
MesaFabApproval.Client/Services/CustomerService.cs
Normal file
51
MesaFabApproval.Client/Services/CustomerService.cs
Normal file
@ -0,0 +1,51 @@
|
||||
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;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user