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 static string BuildKey(string username) => $"{KeyPrefix}{username}";
|
||||
private static string BuildKey(string id) => $"{KeyPrefix}{id}";
|
||||
|
||||
/// <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);
|
||||
|
||||
if (json is null)
|
||||
return new UserPreferencesDto();
|
||||
|
||||
return JsonSerializer.Deserialize<UserPreferencesDto>(json) ?? new UserPreferencesDto();
|
||||
var json = await cache.GetStringAsync(BuildKey(id), ct);
|
||||
if(json is not null && JsonSerializer.Deserialize<UserPreferencesDto>(json) is UserPreferencesDto pref)
|
||||
{
|
||||
return pref;
|
||||
}
|
||||
else
|
||||
{
|
||||
// init new
|
||||
await SaveAsync(id, UserPreferencesDto.Default, ct);
|
||||
return UserPreferencesDto.Default;
|
||||
}
|
||||
}
|
||||
|
||||
/// <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);
|
||||
|
||||
// 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
|
||||
|
||||
Reference in New Issue
Block a user