83 lines
2.2 KiB
C#
83 lines
2.2 KiB
C#
using System.Text.Json;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Caching.Memory;
|
|
using Microsoft.Extensions.Options;
|
|
using Moonlight.Api.Configuration;
|
|
using Moonlight.Api.Database;
|
|
using Moonlight.Api.Database.Entities;
|
|
|
|
namespace Moonlight.Api.Services;
|
|
|
|
public class SettingsService
|
|
{
|
|
private readonly DatabaseRepository<SettingsOption> Repository;
|
|
private readonly IOptions<SettingsOptions> Options;
|
|
private readonly IMemoryCache Cache;
|
|
|
|
private const string CacheKey = "Moonlight.Api.SettingsService.{0}";
|
|
|
|
public SettingsService(
|
|
DatabaseRepository<SettingsOption> repository,
|
|
IOptions<SettingsOptions> options,
|
|
IMemoryCache cache
|
|
)
|
|
{
|
|
Repository = repository;
|
|
Cache = cache;
|
|
Options = options;
|
|
}
|
|
|
|
public async Task<T?> GetValueAsync<T>(string key)
|
|
{
|
|
var cacheKey = string.Format(CacheKey, key);
|
|
|
|
if (Cache.TryGetValue<string>(cacheKey, out var value))
|
|
return JsonSerializer.Deserialize<T>(value!);
|
|
|
|
value = await Repository
|
|
.Query()
|
|
.Where(x => x.Key == key)
|
|
.Select(o => o.ValueJson)
|
|
.FirstOrDefaultAsync();
|
|
|
|
if(string.IsNullOrEmpty(value))
|
|
return default;
|
|
|
|
Cache.Set(
|
|
cacheKey,
|
|
value,
|
|
TimeSpan.FromMinutes(Options.Value.CacheMinutes)
|
|
);
|
|
|
|
return JsonSerializer.Deserialize<T>(value);
|
|
}
|
|
|
|
public async Task SetValueAsync<T>(string key, T value)
|
|
{
|
|
var cacheKey = string.Format(CacheKey, key);
|
|
|
|
var option = await Repository
|
|
.Query()
|
|
.FirstOrDefaultAsync(x => x.Key == key);
|
|
|
|
var json = JsonSerializer.Serialize(value);
|
|
|
|
if (option != null)
|
|
{
|
|
option.ValueJson = json;
|
|
await Repository.UpdateAsync(option);
|
|
}
|
|
else
|
|
{
|
|
option = new SettingsOption()
|
|
{
|
|
Key = key,
|
|
ValueJson = json
|
|
};
|
|
|
|
await Repository.AddAsync(option);
|
|
}
|
|
|
|
Cache.Remove(cacheKey);
|
|
}
|
|
} |