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.
72 lines
2.2 KiB
C#
72 lines
2.2 KiB
C#
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using DbFirst.BlazorWebApp.Models;
|
|
|
|
namespace DbFirst.BlazorWebApp.Services;
|
|
|
|
public class CatalogApiClient
|
|
{
|
|
private readonly HttpClient _httpClient;
|
|
private const string Endpoint = "api/catalogs";
|
|
|
|
public CatalogApiClient(HttpClient httpClient)
|
|
{
|
|
_httpClient = httpClient;
|
|
}
|
|
|
|
public async Task<List<CatalogReadDto>> GetAllAsync()
|
|
{
|
|
var result = await _httpClient.GetFromJsonAsync<List<CatalogReadDto>>(Endpoint);
|
|
return result ?? new List<CatalogReadDto>();
|
|
}
|
|
|
|
public async Task<CatalogReadDto?> GetByIdAsync(int id)
|
|
{
|
|
return await _httpClient.GetFromJsonAsync<CatalogReadDto>($"{Endpoint}/{id}");
|
|
}
|
|
|
|
public async Task<ApiResult<CatalogReadDto?>> CreateAsync(CatalogWriteDto dto)
|
|
{
|
|
var response = await _httpClient.PostAsJsonAsync(Endpoint, dto);
|
|
if (response.IsSuccessStatusCode)
|
|
{
|
|
var payload = await response.Content.ReadFromJsonAsync<CatalogReadDto>();
|
|
return ApiResult<CatalogReadDto?>.Ok(payload);
|
|
}
|
|
|
|
var error = await ApiClientHelper.ReadErrorAsync(response);
|
|
return ApiResult<CatalogReadDto?>.Fail(error);
|
|
}
|
|
|
|
public async Task<ApiResult<bool>> UpdateAsync(int id, CatalogWriteDto dto)
|
|
{
|
|
var response = await _httpClient.PutAsJsonAsync($"{Endpoint}/{id}", dto);
|
|
if (response.IsSuccessStatusCode)
|
|
{
|
|
return ApiResult<bool>.Ok(true);
|
|
}
|
|
|
|
var error = await ApiClientHelper.ReadErrorAsync(response);
|
|
return ApiResult<bool>.Fail(error);
|
|
}
|
|
|
|
public async Task<ApiResult<bool>> DeleteAsync(int id)
|
|
{
|
|
var response = await _httpClient.DeleteAsync($"{Endpoint}/{id}");
|
|
if (response.IsSuccessStatusCode)
|
|
{
|
|
return ApiResult<bool>.Ok(true);
|
|
}
|
|
|
|
var error = await ApiClientHelper.ReadErrorAsync(response);
|
|
return ApiResult<bool>.Fail(error);
|
|
}
|
|
}
|
|
|
|
public record ApiResult<T>(bool Success, T? Value, string? Error)
|
|
{
|
|
public static ApiResult<T> Ok(T? value) => new(true, value, null);
|
|
public static ApiResult<T> Fail(string? error) => new(false, default, error);
|
|
}
|
|
|