namespace zero.Core; using FluentValidation.Results; using Raven.Client.Documents.Indexes; using Raven.Client.Documents.Linq; using System; using System.Collections.Generic; using System.Threading.Tasks; using zero.Core.Database; using zero.Core.Entities; using zero.Core.Validation; public abstract partial class EntityCollection : IEntityCollection where T : ZeroIdEntity, new() { /// public Guid Guid { get; private set; } = Guid.NewGuid(); /// public IZeroDocumentSession Session => Context.Store.Session(); protected record EntityCollectionOptions(bool IncludeInactive); protected IZeroContext Context { get; private set; } protected EntityCollectionOptions Options { get; set; } protected IInterceptorRunner Interceptors { get; private set; } public EntityCollection(ICollectionContext collectionContext) { Context = collectionContext.Context; Interceptors = collectionContext.Interceptors; Options = new(true); } /// /// Get new instance of an entity /// public virtual Task Empty() { return Task.FromResult(new T()); } /// public virtual async Task Validate(T model) { ZeroValidator validator = new(); ValidationRules(validator); return await validator.ValidateAsync(model); } /// /// Create rules for validation /// protected virtual void ValidationRules(ZeroValidator validator) { } /// /// Do only return the model when it is set to active or inactive entities are included with IncludeInactive() /// protected virtual T WhenActive(T model) { return model != null && (Options.IncludeInactive || (model is ZeroEntity ? (model as ZeroEntity).IsActive : true)) ? model : default; } } public interface IEntityCollection where T : ZeroIdEntity, new() { /// /// Get new instance of an entity /// Task Empty(); /// /// Get an entity by Id /// Task Load(string id, string changeVector = null); /// /// Get entities by ids /// Task> Load(IEnumerable ids); /// /// Get entities by query /// Task> Load(ListQuery query); /// /// Get entities by query (by using the specified index) /// Task> Load(ListQuery query) where TIndex : AbstractCommonApiForIndexes, new(); /// /// Get all entities from this collection. /// Warning: Don't use this method for large collections. Stream the results instead. /// Task> LoadAll(); /// /// Stream the collection /// IAsyncEnumerable Stream(); /// /// Stream the collection /// IAsyncEnumerable Stream(Func, IRavenQueryable> expression); /// /// Validates an entity in this collection /// Task Validate(T model); /// /// Updates or creates an entity with an optional validator /// Task> Save(T model); /// /// Deletes an entity /// Task> Delete(T model); /// /// Deletes entities /// Task Delete(IEnumerable models); /// /// Deletes an entity by Id /// Task> Delete(string id); /// /// Deletes entities by Id /// Task Delete(IEnumerable ids); }