mirror of
https://github.com/thebreaddev/Supercell.GUT.git
synced 2024-11-10 07:44:37 +00:00
281d2789ea
not finished. early wip state
54 lines
1.9 KiB
C#
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;
|
|
}
|
|
}
|