Refactored code to use C# 12 collection expressions ([]) for initializing empty lists and dictionaries instead of the older constructors. This change modernizes and simplifies collection initialization across models, services, and API clients without altering any logic.
64 lines
2.1 KiB
C#
64 lines
2.1 KiB
C#
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using DbFirst.BlazorWebApp.Models;
|
|
|
|
namespace DbFirst.BlazorWebApp.Services;
|
|
|
|
public class CatalogApiClient : ICatalogApiClient
|
|
{
|
|
private readonly HttpClient _httpClient;
|
|
private const string Endpoint = "api/catalogs";
|
|
|
|
public CatalogApiClient(HttpClient httpClient)
|
|
{
|
|
_httpClient = httpClient;
|
|
}
|
|
|
|
public async Task<List<CatalogReadDto>> GetAllAsync(CancellationToken ct = default)
|
|
{
|
|
var result = await _httpClient.GetFromJsonAsync<List<CatalogReadDto>>(Endpoint, ct);
|
|
return result ?? [];
|
|
}
|
|
|
|
public async Task<CatalogReadDto?> GetByIdAsync(int id, CancellationToken ct = default)
|
|
{
|
|
return await _httpClient.GetFromJsonAsync<CatalogReadDto>($"{Endpoint}/{id}", ct);
|
|
}
|
|
|
|
public async Task<ApiResult<CatalogReadDto?>> CreateAsync(CatalogWriteDto dto, CancellationToken ct = default)
|
|
{
|
|
var response = await _httpClient.PostAsJsonAsync(Endpoint, dto, ct);
|
|
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, CancellationToken ct = default)
|
|
{
|
|
var response = await _httpClient.PutAsJsonAsync($"{Endpoint}/{id}", dto, ct);
|
|
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, CancellationToken ct = default)
|
|
{
|
|
var response = await _httpClient.DeleteAsync($"{Endpoint}/{id}", ct);
|
|
if (response.IsSuccessStatusCode)
|
|
{
|
|
return ApiResult<bool>.Ok(true);
|
|
}
|
|
|
|
var error = await ApiClientHelper.ReadErrorAsync(response);
|
|
return ApiResult<bool>.Fail(error);
|
|
}
|
|
} |