81 lines
2.9 KiB
C#

#if DOTNET || UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX || UNITY_STANDALONE_OSX
using System;
using System.Collections.Generic;
using System.Linq;
using MongoDB.Driver;
namespace ET.Server
{
[EnableClass]
public sealed class MongoDBComponent : IDBComponent
{
private readonly IMongoDatabase database;
public MongoDBComponent(string connectionString, string dbName)
{
if (string.IsNullOrWhiteSpace(connectionString))
{
throw new ArgumentException("Mongo connection string is empty.", nameof(connectionString));
}
if (string.IsNullOrWhiteSpace(dbName))
{
throw new ArgumentException("Mongo DB name is empty.", nameof(dbName));
}
MongoClient client = new(connectionString);
this.database = client.GetDatabase(dbName);
}
public async ETTask Save<T>(long entityId, T entity) where T : class
{
DbEntityRecord record = new()
{
Id = entityId,
Payload = MongoHelper.Serialize(entity)
};
IMongoCollection<DbEntityRecord> collection = this.GetCollection<T>();
await collection.ReplaceOneAsync(x => x.Id == entityId, record, new ReplaceOptions { IsUpsert = true });
}
public async ETTask<T> QueryByEntityId<T>(long entityId) where T : class
{
IMongoCollection<DbEntityRecord> collection = this.GetCollection<T>();
DbEntityRecord record = await collection.Find(x => x.Id == entityId).FirstOrDefaultAsync();
return record == null ? null : MongoHelper.Deserialize<T>(record.Payload);
}
public async ETTask<List<T>> Query<T>(Func<T, bool> predicate = null) where T : class
{
IMongoCollection<DbEntityRecord> collection = this.GetCollection<T>();
List<DbEntityRecord> records = await collection.Find(Builders<DbEntityRecord>.Filter.Empty).ToListAsync();
IEnumerable<T> entities = records.Select(x => MongoHelper.Deserialize<T>(x.Payload));
if (predicate != null)
{
entities = entities.Where(predicate);
}
return entities.ToList();
}
public ETTask Update<T>(long entityId, T entity) where T : class
{
return this.Save(entityId, entity);
}
public async ETTask Delete<T>(long entityId) where T : class
{
IMongoCollection<DbEntityRecord> collection = this.GetCollection<T>();
await collection.DeleteOneAsync(x => x.Id == entityId);
}
private IMongoCollection<DbEntityRecord> GetCollection<T>() where T : class
{
string collectionName = typeof(T).Name;
return this.database.GetCollection<DbEntityRecord>(collectionName);
}
}
}
#endif