Files
EnvelopeGenerator/EnvelopeGenerator.ReceiverUI/Services/EnvelopeService.cs
TekH 95c8e15887 Add EnvelopeDto and EnvelopeService for API integration
Introduced the `EnvelopeDto` class to represent envelope data with JSON property mappings. Added the `EnvelopeService` class to handle API interactions, including fetching envelopes with optional filters and query string construction using `Microsoft.AspNetCore.WebUtilities`. Updated the project file to include the required package reference for query string manipulation.
2026-06-15 15:40:59 +02:00

73 lines
2.3 KiB
C#

using System.Net.Http.Json;
using System.Text.Json;
using EnvelopeGenerator.ReceiverUI.Models;
using EnvelopeGenerator.ReceiverUI.Options;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Options;
namespace EnvelopeGenerator.ReceiverUI.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);
}
}