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

53 lines
1.8 KiB
C#

using System.Text.Json;
namespace MesaFabApproval.Client.Services;
public interface IECNService {
Task<string> ECNNumberIsValidStr(int ecnNumber);
Task<bool> ECNNumberIsValid(int number);
}
public class ECNService : IECNService {
private readonly IHttpClientFactory _httpClientFactory;
public ECNService(IHttpClientFactory httpClientFactory) {
_httpClientFactory = httpClientFactory ??
throw new ArgumentNullException("IHttpClientFactory not injected");
}
public async Task<string> ECNNumberIsValidStr(int ecnNumber) {
if (ecnNumber <= 0 || !await ECNNumberIsValid(ecnNumber))
return $"{ecnNumber} is not a valid ECN#";
return null;
}
public async Task<bool> ECNNumberIsValid(int number) {
if (number <= 0) return false;
try {
HttpClient httpClient = _httpClientFactory.CreateClient("API");
HttpRequestMessage requestMessage = new(HttpMethod.Get, $"ecn/isValidEcnNumber?number={number}");
HttpResponseMessage responseMessage = await httpClient.SendAsync(requestMessage);
if (responseMessage.IsSuccessStatusCode) {
string responseContent = await responseMessage.Content.ReadAsStringAsync();
JsonSerializerOptions jsonSerializerOptions = new() {
PropertyNameCaseInsensitive = true
};
bool isValid = JsonSerializer.Deserialize<bool>(responseContent, jsonSerializerOptions);
return isValid;
} else {
throw new Exception(responseMessage.ReasonPhrase);
}
} catch (Exception ex) {
throw new Exception($"Unable to determine if {number} is a valid ECN#, because {ex.Message}");
}
}
}