69 lines
2.1 KiB
C#
69 lines
2.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
|
|
namespace ET.Server
|
|
{
|
|
[EnableClass]
|
|
public sealed class MemoryDBComponent : IDBComponent
|
|
{
|
|
private readonly Dictionary<string, Dictionary<long, byte[]>> data = new();
|
|
|
|
public async ETTask Save<T>(long entityId, T entity) where T : class
|
|
{
|
|
Dictionary<long, byte[]> map = this.GetBucket<T>();
|
|
map[entityId] = MongoHelper.Serialize(entity);
|
|
await ETTask.CompletedTask;
|
|
}
|
|
|
|
public async ETTask<T> QueryByEntityId<T>(long entityId) where T : class
|
|
{
|
|
await ETTask.CompletedTask;
|
|
Dictionary<long, byte[]> map = this.GetBucket<T>();
|
|
if (!map.TryGetValue(entityId, out byte[] bytes))
|
|
{
|
|
return null;
|
|
}
|
|
|
|
return MongoHelper.Deserialize<T>(bytes);
|
|
}
|
|
|
|
public async ETTask<List<T>> Query<T>(Func<T, bool> predicate = null) where T : class
|
|
{
|
|
await ETTask.CompletedTask;
|
|
Dictionary<long, byte[]> map = this.GetBucket<T>();
|
|
IEnumerable<T> entities = map.Values.Select(MongoHelper.Deserialize<T>);
|
|
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
|
|
{
|
|
Dictionary<long, byte[]> map = this.GetBucket<T>();
|
|
map.Remove(entityId);
|
|
await ETTask.CompletedTask;
|
|
}
|
|
|
|
private Dictionary<long, byte[]> GetBucket<T>() where T : class
|
|
{
|
|
string key = typeof(T).Name;
|
|
if (!this.data.TryGetValue(key, out Dictionary<long, byte[]> bucket))
|
|
{
|
|
bucket = new Dictionary<long, byte[]>();
|
|
this.data[key] = bucket;
|
|
}
|
|
|
|
return bucket;
|
|
}
|
|
}
|
|
}
|