48 lines
1.6 KiB
C#
48 lines
1.6 KiB
C#
using Flypaper.Core.Settings;
|
|
using Flypaper.Storage.Entities;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace Flypaper.Storage.Settings;
|
|
|
|
public sealed partial class RuntimeSettingsStore(
|
|
IDbContextFactory<FlypaperDbContext> dbContextFactory,
|
|
DbConfigurationSource source,
|
|
ILogger<RuntimeSettingsStore> logger)
|
|
{
|
|
public async Task SaveAsync(RuntimeSettings settings, CancellationToken ct = default)
|
|
{
|
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
|
await using var transaction = await db.Database.BeginTransactionAsync(ct);
|
|
await db.Settings.ExecuteDeleteAsync(ct);
|
|
db.Settings.AddRange(settings.ToConfiguration().Select(pair => new SettingEntity { Key = pair.Key, Value = pair.Value }));
|
|
await db.SaveChangesAsync(ct);
|
|
await transaction.CommitAsync(ct);
|
|
Reload();
|
|
}
|
|
|
|
public async Task ResetAsync(CancellationToken ct = default)
|
|
{
|
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
|
await db.Settings.ExecuteDeleteAsync(ct);
|
|
Reload();
|
|
}
|
|
|
|
public async Task<bool> HasOverridesAsync(CancellationToken ct = default)
|
|
{
|
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
|
return await db.Settings.AnyAsync(ct);
|
|
}
|
|
|
|
private void Reload()
|
|
{
|
|
if (!source.TryReload())
|
|
{
|
|
LogReloadFailed();
|
|
}
|
|
}
|
|
|
|
[LoggerMessage(Level = LogLevel.Warning, Message = "Settings were saved but could not be reloaded from the database; previous values stay active")]
|
|
private partial void LogReloadFailed();
|
|
}
|