44 lines
1.2 KiB
C#
44 lines
1.2 KiB
C#
using System.Text.Json;
|
|
using RecNet.Application.Common.Interfaces;
|
|
using RecNet.Domain.Configuration;
|
|
|
|
namespace RecNet.Infrastructure.Services.Configuration;
|
|
|
|
public class ConfigService(IServerConfigRepository repository) : IConfigService
|
|
{
|
|
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
|
|
|
|
public async Task<T?> GetAsync<T>(string key, CancellationToken ct = default)
|
|
{
|
|
var config = await repository.GetAsync(key, ct);
|
|
if (config == null)
|
|
return default;
|
|
|
|
return JsonSerializer.Deserialize<T>(config.Value, JsonOptions);
|
|
}
|
|
|
|
public async Task<T> GetAsync<T>(
|
|
string key,
|
|
T defaultValue,
|
|
CancellationToken ct = default)
|
|
{
|
|
var config = await repository.GetAsync(key, ct);
|
|
if (config == null)
|
|
return defaultValue;
|
|
|
|
return JsonSerializer.Deserialize<T>(config.Value, JsonOptions) ?? defaultValue;
|
|
}
|
|
|
|
public async Task SetAsync<T>(
|
|
string key,
|
|
T value,
|
|
CancellationToken ct = default)
|
|
{
|
|
var json = JsonSerializer.Serialize(value, JsonOptions);
|
|
|
|
await repository.SetAsync(key, json, ct);
|
|
|
|
await repository.SaveChangesAsync(ct);
|
|
}
|
|
}
|