Refactored error handling logic for API responses into a new static ApiClientHelper class, consolidating the ReadErrorAsync method and ProblemDetailsDto. Updated CatalogApiClient and MassDataApiClient to use the shared helper, removing redundant local methods and classes. This change improves consistency, reduces duplication, and streamlines error message formatting across the application.
69 lines
2.1 KiB
C#
69 lines
2.1 KiB
C#
using System.Net.Http.Json;
|
|
using DbFirst.BlazorWebApp.Models;
|
|
|
|
namespace DbFirst.BlazorWebApp.Services;
|
|
|
|
public class MassDataApiClient
|
|
{
|
|
private readonly HttpClient _httpClient;
|
|
private const string Endpoint = "api/massdata";
|
|
|
|
public MassDataApiClient(HttpClient httpClient)
|
|
{
|
|
_httpClient = httpClient;
|
|
}
|
|
|
|
public async Task<int> GetCountAsync()
|
|
{
|
|
var result = await _httpClient.GetFromJsonAsync<int?>("api/massdata/count");
|
|
return result ?? 0;
|
|
}
|
|
|
|
public async Task<List<MassDataReadDto>> GetAllAsync(int? skip, int? take)
|
|
{
|
|
var query = new List<string>();
|
|
if (skip.HasValue)
|
|
{
|
|
query.Add($"skip={skip.Value}");
|
|
}
|
|
if (take.HasValue)
|
|
{
|
|
query.Add($"take={take.Value}");
|
|
}
|
|
|
|
var url = query.Count == 0 ? Endpoint : $"{Endpoint}?{string.Join("&", query)}";
|
|
var result = await _httpClient.GetFromJsonAsync<List<MassDataReadDto>>(url);
|
|
return result ?? new List<MassDataReadDto>();
|
|
}
|
|
|
|
public async Task<ApiResult<MassDataReadDto?>> UpsertAsync(MassDataWriteDto dto)
|
|
{
|
|
var response = await _httpClient.PostAsJsonAsync($"{Endpoint}/upsert", dto);
|
|
if (response.IsSuccessStatusCode)
|
|
{
|
|
var payload = await response.Content.ReadFromJsonAsync<MassDataReadDto>();
|
|
return ApiResult<MassDataReadDto?>.Ok(payload);
|
|
}
|
|
|
|
var error = await ApiClientHelper.ReadErrorAsync(response);
|
|
return ApiResult<MassDataReadDto?>.Fail(error);
|
|
}
|
|
|
|
public async Task<MassDataReadDto?> GetByCustomerNameAsync(string customerName)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(customerName))
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var response = await _httpClient.GetAsync($"{Endpoint}/{Uri.EscapeDataString(customerName)}");
|
|
if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
response.EnsureSuccessStatusCode();
|
|
return await response.Content.ReadFromJsonAsync<MassDataReadDto>();
|
|
}
|
|
}
|