44 lines
1.6 KiB
C#
44 lines
1.6 KiB
C#
using MongoDB.Driver;
|
|
using WorkTracker.Domain;
|
|
|
|
namespace WorkTracker.Services.Settings;
|
|
|
|
public sealed class MongoAppSettingsService : IAppSettingsService
|
|
{
|
|
private const string DefaultSettingsId = "global";
|
|
private readonly IMongoCollection<AppSettingsDocument> appSettingsCollection;
|
|
|
|
public MongoAppSettingsService(IMongoDatabase database)
|
|
{
|
|
appSettingsCollection = database.GetCollection<AppSettingsDocument>("app_settings");
|
|
}
|
|
|
|
public async Task<AppSettingsDocument> GetAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
var filter = Builders<AppSettingsDocument>.Filter.Eq(x => x.Id, DefaultSettingsId);
|
|
var settings = await appSettingsCollection.Find(filter).FirstOrDefaultAsync(cancellationToken);
|
|
|
|
if (settings is not null)
|
|
{
|
|
return settings;
|
|
}
|
|
|
|
var defaults = new AppSettingsDocument();
|
|
await appSettingsCollection.InsertOneAsync(defaults, cancellationToken: cancellationToken);
|
|
return defaults;
|
|
}
|
|
|
|
public async Task<AppSettingsDocument> SaveAsync(AppSettingsDocument settings, CancellationToken cancellationToken = default)
|
|
{
|
|
var existing = await GetAsync(cancellationToken);
|
|
|
|
settings.Id = DefaultSettingsId;
|
|
settings.CreatedAtUtc = existing.CreatedAtUtc;
|
|
settings.UpdatedAtUtc = DateTimeOffset.UtcNow;
|
|
|
|
var filter = Builders<AppSettingsDocument>.Filter.Eq(x => x.Id, DefaultSettingsId);
|
|
await appSettingsCollection.ReplaceOneAsync(filter, settings, new ReplaceOptions { IsUpsert = true }, cancellationToken);
|
|
|
|
return settings;
|
|
}
|
|
}
|