Files
EnvelopeGenerator/EnvelopeGenerator.Server/EnvelopeGenerator.Server.Client/Services/EnvelopeService.cs
TekH a4b218b9f3 Add new namespaces to EnvelopeService.cs
Included `EnvelopeGenerator.Application.Common.Dto`, `EnvelopeGenerator.Server.Client.Models`, `EnvelopeGenerator.Server.Client.Options`, and `Microsoft.AspNetCore.WebUtilities` to support new functionality or dependencies in the `EnvelopeService.cs` file.
2026-06-25 15:35:36 +02:00

74 lines
2.3 KiB
C#

using System.Net.Http.Json;
using System.Text.Json;
using EnvelopeGenerator.Application.Common.Dto;
using EnvelopeGenerator.Server.Client.Models;
using EnvelopeGenerator.Server.Client.Options;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Options;
namespace EnvelopeGenerator.Server.Client.Services;
/// <summary>
/// Retrieves <see cref="EnvelopeDto"/>s from the API.
/// </summary>
public class EnvelopeService
{
private readonly HttpClient _http;
private readonly ApiOptions _apiOptions;
private static readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web);
public EnvelopeService(HttpClient http, IOptions<ApiOptions> apiOptions)
{
_http = http;
_apiOptions = apiOptions.Value;
}
/// <summary>
/// Fetches envelopes from the API with optional filters.
/// </summary>
/// <exception cref="HttpRequestException">Thrown when the API request fails.</exception>
public async Task<IEnumerable<EnvelopeDto>?> GetAsync(
int? id = null,
string? uuid = null,
bool? onlyActive = null,
bool? onlyCompleted = null,
CancellationToken cancel = default)
{
var baseUrl = $"{_apiOptions.BaseUrl}/api/Envelope";
var queryParams = new Dictionary<string, string?>();
if (id.HasValue)
{
queryParams["Id"] = id.Value.ToString();
}
if (!string.IsNullOrEmpty(uuid))
{
queryParams["Uuid"] = uuid;
}
if (onlyActive.HasValue)
{
queryParams["OnlyActive"] = onlyActive.Value.ToString();
}
if (onlyCompleted.HasValue)
{
queryParams["OnlyCompleted"] = onlyCompleted.Value.ToString();
}
var url = QueryHelpers.AddQueryString(baseUrl, queryParams);
var response = await _http.GetAsync(url, cancel);
if (!response.IsSuccessStatusCode)
{
var statusCode = (int)response.StatusCode;
var reasonPhrase = response.ReasonPhrase ?? "Unknown error";
throw new HttpRequestException(
$"Failed to load envelopes. Status: {statusCode} ({reasonPhrase})",
null,
response.StatusCode);
}
return await response.Content.ReadFromJsonAsync<IEnumerable<EnvelopeDto>>(_jsonOptions, cancel);
}
}