| 1 |
using System.Text.Json; |
| 2 |
using Blog.Models; |
| 3 |
using Microsoft.Extensions.Caching.Hybrid; |
| 4 |
|
| 5 |
namespace Blog.Services; |
| 6 |
|
| 7 |
public class BrpService(HybridCache cache, HttpClient client) |
| 8 |
{ |
| 9 |
public async Task<BRPEntry[]> GetBrpEntriesAsync(CancellationToken cancellationToken = default) |
| 10 |
{ |
| 11 |
return await cache.GetOrCreateAsync( |
| 12 |
"brp", |
| 13 |
async cancel => |
| 14 |
{ |
| 15 |
await using FileStream filestream = File.Open("Resources/test-data.json", FileMode.Open); |
| 16 |
var entries = await JsonSerializer.DeserializeAsync<BRPEntry[]>(filestream, cancellationToken: cancel) |
| 17 |
.ConfigureAwait(false); |
| 18 |
return entries ?? []; |
| 19 |
}, |
| 20 |
cancellationToken: cancellationToken) |
| 21 |
.ConfigureAwait(false); |
| 22 |
} |
| 23 |
|
| 24 |
public async Task<(JsonDocument request, JsonDocument response)> GetBrpEntryAsync(string bsn, CancellationToken cancellationToken = default) |
| 25 |
{ |
| 26 |
return await cache.GetOrCreateAsync( |
| 27 |
$"brp/{bsn}", |
| 28 |
bsn, |
| 29 |
async (state, cancel) => await FetchBrpEntryAsync(state, cancel), |
| 30 |
cancellationToken: cancellationToken) |
| 31 |
.ConfigureAwait(false); |
| 32 |
} |
| 33 |
|
| 34 |
private async Task<(JsonDocument request, JsonDocument response)> FetchBrpEntryAsync(string bsn, CancellationToken cancellationToken) |
| 35 |
{ |
| 36 |
var response = await client.PostAsJsonAsync( |
| 37 |
"haalcentraal/api/brp/personen", |
| 38 |
new RaadpleegMetBurgerservicenummer(bsn), |
| 39 |
cancellationToken) |
| 40 |
.ConfigureAwait(false); |
| 41 |
|
| 42 |
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); |
| 43 |
var responseDocument = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false); |
| 44 |
|
| 45 |
await using var requestStream = await response.RequestMessage!.Content!.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); |
| 46 |
var requestDocument = await JsonDocument.ParseAsync(requestStream, cancellationToken: cancellationToken).ConfigureAwait(false); |
| 47 |
|
| 48 |
return (requestDocument, responseDocument); |
| 49 |
} |
| 50 |
} |