Supercell.GUT/Supercell.GUT.Server/Database/DatabaseManager.cs
BreadDEV 281d2789ea [v0.1.0] database implementation
not finished. early wip state
2024-03-06 22:00:12 +07:00

54 lines
1.9 KiB
C#

using Microsoft.Extensions.Options;
using MongoDB.Driver;
using Supercell.GUT.Server.Database.Document;
using Supercell.GUT.Server.Database.Options;
namespace Supercell.GUT.Server.Database;
public class DatabaseManager
{
private const string IdentifierCounterCollection = "t_id_counter";
private static readonly FindOneAndUpdateOptions<IdentifierCounterDocument> s_counterUpdateOptions = new() { ReturnDocument = ReturnDocument.After };
private readonly DatabaseOptions _options;
private readonly MongoClient _client;
private readonly IMongoDatabase _database;
private readonly IMongoCollection<IdentifierCounterDocument> _idCounters;
public DatabaseManager(IOptions<DatabaseOptions> options)
{
_options = options.Value;
_client = new MongoClient(_options.MongoConnectionString);
_database = _client.GetDatabase(_options.DatabaseName);
_idCounters = _database.GetCollection<IdentifierCounterDocument>(IdentifierCounterCollection);
}
public IMongoCollection<TDatabaseDocument> GetCollection<TDatabaseDocument>(string collectionName) where TDatabaseDocument : IDatabaseDocument
{
return _database.GetCollection<TDatabaseDocument>(collectionName);
}
public async Task<int> GetNextLowIdAsync(string counterName)
{
var cursor = await _idCounters.FindAsync(doc => doc.CounterName == counterName);
if (!cursor.Any())
{
await _idCounters.InsertOneAsync(new IdentifierCounterDocument
{
CounterName = counterName,
CurrentLowId = 0
});
}
IdentifierCounterDocument? document = await _idCounters.FindOneAndUpdateAsync<IdentifierCounterDocument>(
x => x.CounterName == counterName,
Builders<IdentifierCounterDocument>.Update.Inc(nameof(IdentifierCounterDocument.CurrentLowId), 1),
s_counterUpdateOptions);
return document.CurrentLowId;
}
}