Refactored the GetAllAsync method to use a Dictionary and QueryHelpers.AddQueryString for building query strings, replacing manual string concatenation. This improves code clarity and reduces the risk of formatting errors.
64 lines
2.2 KiB
C#
64 lines
2.2 KiB
C#
using DbFirst.BlazorWebApp.Models;
|
|
using DbFirst.Contracts.MassData;
|
|
using Microsoft.AspNetCore.WebUtilities;
|
|
|
|
namespace DbFirst.BlazorWebApp.Services;
|
|
|
|
public class MassDataApiClient : IMassDataApiClient
|
|
{
|
|
private readonly HttpClient _httpClient;
|
|
private const string Endpoint = "api/massdata";
|
|
|
|
public MassDataApiClient(HttpClient httpClient)
|
|
{
|
|
_httpClient = httpClient;
|
|
}
|
|
|
|
public async Task<int> GetCountAsync(CancellationToken ct = default)
|
|
{
|
|
var result = await _httpClient.GetFromJsonAsync<int?>("api/massdata/count", ct);
|
|
return result ?? 0;
|
|
}
|
|
|
|
public async Task<List<MassDataReadDto>> GetAllAsync(int? skip, int? take, CancellationToken ct = default)
|
|
{
|
|
var query = new Dictionary<string, string?>();
|
|
if (skip.HasValue) query["skip"] = skip.Value.ToString();
|
|
if (take.HasValue) query["take"] = take.Value.ToString();
|
|
|
|
var url = QueryHelpers.AddQueryString(Endpoint, query);
|
|
var result = await _httpClient.GetFromJsonAsync<List<MassDataReadDto>>(url, ct);
|
|
return result ?? [];
|
|
}
|
|
|
|
public async Task<ApiResult<MassDataReadDto?>> UpsertAsync(MassDataWriteDto dto, CancellationToken ct = default)
|
|
{
|
|
var response = await _httpClient.PostAsJsonAsync($"{Endpoint}/upsert", dto, ct);
|
|
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, CancellationToken ct = default)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(customerName))
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var response = await _httpClient.GetAsync($"{Endpoint}/{Uri.EscapeDataString(customerName)}", ct);
|
|
if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
response.EnsureSuccessStatusCode();
|
|
return await response.Content.ReadFromJsonAsync<MassDataReadDto>();
|
|
}
|
|
}
|