Files
DbFirst/DbFirst.BlazorWebApp/Services/CatalogApiClient.cs
OlgunR 45011122b2 Refactor API clients to use primary constructor for HttpClient
Refactored CatalogApiClient, DashboardApiClient, LayoutApiClient, and MassDataApiClient to use C# primary constructor syntax for injecting HttpClient. Removed private _httpClient fields and updated all usages to reference the constructor parameter directly. This change simplifies the code and modernizes dependency injection without altering any API logic.
2026-05-11 17:08:52 +02:00

57 lines
2.0 KiB
C#

using DbFirst.BlazorWebApp.Models;
using DbFirst.Contracts.Catalogs;
namespace DbFirst.BlazorWebApp.Services;
public class CatalogApiClient(HttpClient httpClient) : ICatalogApiClient
{
private const string Endpoint = "api/catalogs";
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);
}
}