using FluentValidation; using Raven.Client; using Raven.Client.Documents; using Raven.Client.Documents.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using zero.Core.Entities; using zero.Core.Extensions; namespace zero.Core.Collections { public abstract class CollectionCacheBase : CollectionBase, ICollectionBase, IDisposable where T : IZeroEntity { public CollectionCacheBase(IZeroContext context, ICollectionInterceptorHandler interceptorHandler, IValidator validator = null) : base(context, interceptorHandler, validator) { } protected List Items { get; set; } protected async Task Preload() { if (Items == null || !Items.Any()) { Items = await Session.Query().ToListAsync(); } } /// public override void ApplyScope(string scope) { Items = null; base.ApplyScope(scope); } /// public override async Task GetById(string id) { await Preload(); if (id.IsNullOrWhiteSpace()) { return default; } return Items.FirstOrDefault(x => x.Id == id); } /// public override async Task> GetByIds(params string[] ids) { await Preload(); Dictionary models = Items.Where(x => ids.Contains(x.Id)).ToDictionary(x => x.Id, x => x); Dictionary result = new Dictionary(); foreach (string id in ids) { models.TryGetValue(id, out T model); result.Add(id, model); } return result; } /// public override async Task> GetByQuery(ListQuery query) { return await Session.Query().OrderByDescending(x => x.CreatedDate).ToQueriedListAsync(query); } /// public override async Task> GetAll() { await Preload(); return Items; } /// public override async Task> Save(T model) { EntityResult result = await Save(model); if (result.IsSuccess) { Items = null; } return result; } /// public override async Task> DeleteById(string id) { EntityResult result = await DeleteById(id); if (result.IsSuccess) { Items = null; } return result; } /// public override async Task DeleteByIds(params string[] ids) { int successCount = await DeleteByIds(ids); if (successCount > 0) { Items = null; } return successCount; } /// public override async Task> Purge(string querySuffix = null, Parameters parameters = null) { EntityResult result = await Purge(querySuffix, parameters); if (result.IsSuccess) { Items = null; } return result; } } }