using System; using System.Collections.Generic; using System.Linq; namespace ET.Server { [EnableClass] public sealed class MemoryDBComponent : IDBComponent { private readonly Dictionary> data = new(); public async ETTask Save(long entityId, T entity) where T : class { Dictionary map = this.GetBucket(); map[entityId] = MongoHelper.Serialize(entity); await ETTask.CompletedTask; } public async ETTask QueryByEntityId(long entityId) where T : class { await ETTask.CompletedTask; Dictionary map = this.GetBucket(); if (!map.TryGetValue(entityId, out byte[] bytes)) { return null; } return MongoHelper.Deserialize(bytes); } public async ETTask> Query(Func predicate = null) where T : class { await ETTask.CompletedTask; Dictionary map = this.GetBucket(); IEnumerable entities = map.Values.Select(MongoHelper.Deserialize); if (predicate != null) { entities = entities.Where(predicate); } return entities.ToList(); } public ETTask Update(long entityId, T entity) where T : class { return this.Save(entityId, entity); } public async ETTask Delete(long entityId) where T : class { Dictionary map = this.GetBucket(); map.Remove(entityId); await ETTask.CompletedTask; } private Dictionary GetBucket() where T : class { string key = typeof(T).Name; if (!this.data.TryGetValue(key, out Dictionary bucket)) { bucket = new Dictionary(); this.data[key] = bucket; } return bucket; } } }