using System.Text.Json; using Blog.Models; using Microsoft.Extensions.Caching.Hybrid; namespace Blog.Services; public class BrpService(HybridCache cache, HttpClient client) { public async Task GetBrpEntriesAsync(CancellationToken cancellationToken = default) { return await cache.GetOrCreateAsync( "brp", async cancel => { await using FileStream filestream = File.Open("Resources/test-data.json", FileMode.Open); var entries = await JsonSerializer.DeserializeAsync(filestream, cancellationToken: cancel) .ConfigureAwait(false); return entries ?? []; }, cancellationToken: cancellationToken) .ConfigureAwait(false); } public async Task<(JsonDocument request, JsonDocument response)> GetBrpEntryAsync(string bsn, CancellationToken cancellationToken = default) { return await cache.GetOrCreateAsync( $"brp/{bsn}", bsn, async (state, cancel) => await FetchBrpEntryAsync(state, cancel), cancellationToken: cancellationToken) .ConfigureAwait(false); } private async Task<(JsonDocument request, JsonDocument response)> FetchBrpEntryAsync(string bsn, CancellationToken cancellationToken) { var response = await client.PostAsJsonAsync( "haalcentraal/api/brp/personen", new RaadpleegMetBurgerservicenummer(bsn), cancellationToken) .ConfigureAwait(false); await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); var responseDocument = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false); await using var requestStream = await response.RequestMessage!.Content!.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); var requestDocument = await JsonDocument.ParseAsync(requestStream, cancellationToken: cancellationToken).ConfigureAwait(false); return (requestDocument, responseDocument); } }