SF-74: Infrastructure — UserPreferencesService (IDistributedCache, no try-catch)
This commit is contained in:
@@ -16,26 +16,31 @@ public sealed class UserPreferencesService(IDistributedCache cache) : IUserPrefe
|
|||||||
{
|
{
|
||||||
private const string KeyPrefix = "signflow.user-preferences:";
|
private const string KeyPrefix = "signflow.user-preferences:";
|
||||||
|
|
||||||
private static string BuildKey(string username) => $"{KeyPrefix}{username}";
|
private static string BuildKey(string id) => $"{KeyPrefix}{id}";
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public async Task<UserPreferencesDto> GetAsync(string username, CancellationToken ct = default)
|
public async Task<UserPreferencesDto> GetOrCreateAsync(string id, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
var json = await cache.GetStringAsync(BuildKey(username), ct);
|
var json = await cache.GetStringAsync(BuildKey(id), ct);
|
||||||
|
if(json is not null && JsonSerializer.Deserialize<UserPreferencesDto>(json) is UserPreferencesDto pref)
|
||||||
if (json is null)
|
{
|
||||||
return new UserPreferencesDto();
|
return pref;
|
||||||
|
}
|
||||||
return JsonSerializer.Deserialize<UserPreferencesDto>(json) ?? new UserPreferencesDto();
|
else
|
||||||
|
{
|
||||||
|
// init new
|
||||||
|
await SaveAsync(id, UserPreferencesDto.Default, ct);
|
||||||
|
return UserPreferencesDto.Default;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public async Task SaveAsync(string username, UserPreferencesDto preferences, CancellationToken ct = default)
|
public async Task SaveAsync(string id, UserPreferencesDto preferences, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
var json = JsonSerializer.Serialize(preferences);
|
var json = JsonSerializer.Serialize(preferences);
|
||||||
|
|
||||||
// No expiration — preferences are stored indefinitely.
|
// No expiration — preferences are stored indefinitely.
|
||||||
await cache.SetStringAsync(BuildKey(username), json, new DistributedCacheEntryOptions(), ct);
|
await cache.SetStringAsync(BuildKey(id), json, new DistributedCacheEntryOptions(), ct);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|||||||
Reference in New Issue
Block a user