SF-74: Client — CustomImagesService (in-memory cache, GET /api/CustomImages), DI registration
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace EnvelopeGenerator.Server.Client.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Fetches and caches the CustomImages configuration (signFLOW + company logos)
|
||||
/// from GET /api/CustomImages.
|
||||
///
|
||||
/// Config changes rarely (deployment-time only), so results are cached in-memory
|
||||
/// for the lifetime of the service (WASM app session). No TTL needed.
|
||||
/// </summary>
|
||||
public class CustomImagesService(IHttpClientFactory clientFactory)
|
||||
{
|
||||
private static readonly JsonSerializerOptions _json = new(JsonSerializerDefaults.Web);
|
||||
private const string Endpoint = "/api/CustomImages";
|
||||
|
||||
private CustomImagesDto? _cached;
|
||||
|
||||
/// <summary>
|
||||
/// Returns logo configuration. Fetches once from server; all subsequent calls
|
||||
/// are served from memory with zero network overhead.
|
||||
/// Returns defaults (empty Src) on auth failure (401) — components must handle gracefully.
|
||||
/// </summary>
|
||||
public async Task<CustomImagesDto> GetAsync(CancellationToken ct = default)
|
||||
{
|
||||
if (_cached is not null)
|
||||
return _cached;
|
||||
|
||||
try
|
||||
{
|
||||
var client = clientFactory.CreateClient("EnvelopeGenerator.Server");
|
||||
var response = await client.GetAsync(Endpoint, ct);
|
||||
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
// Not authenticated yet (login page) — return defaults silently.
|
||||
_cached = new CustomImagesDto();
|
||||
return _cached;
|
||||
}
|
||||
|
||||
_cached = await response.Content.ReadFromJsonAsync<CustomImagesDto>(_json, ct)
|
||||
?? new CustomImagesDto();
|
||||
return _cached;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// Network error or server unavailable — return defaults so UI still renders.
|
||||
return new CustomImagesDto();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Call after logout to force re-fetch on next login.</summary>
|
||||
public void Invalidate() => _cached = null;
|
||||
}
|
||||
Reference in New Issue
Block a user