using FluentValidation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using zero.Core.Entities;
namespace zero.Core.Collections
{
public class CollectionInterceptorHandler : ICollectionInterceptorHandler
{
///
public IEnumerable Interceptors { get; private set; }
public CollectionInterceptorHandler(IEnumerable items)
{
Interceptors = items;
}
///
public async Task> Handle(Expression>>> intercept)
{
Func>> func = default;
foreach (ICollectionInterceptor interceptor in ForType(typeof(T)))
{
if (func == default)
{
func = intercept.Compile();
}
EntityResult result = await func(interceptor);
if (result != default)
{
return result;
}
}
return default;
}
///
public async Task Handle(Expression> intercept)
{
Func func = default;
foreach (ICollectionInterceptor interceptor in ForType(typeof(T)))
{
if (func == default)
{
func = intercept.Compile();
}
await func(interceptor);
}
}
///
/// Get all interceptors for a certain type
///
IEnumerable ForType(Type targetType)
{
return Interceptors.Where(item => item.Types.Count == 0 || item.Types.Any(type => targetType.IsAssignableFrom(type)));
}
}
public interface ICollectionInterceptorHandler
{
///
/// All registered interceptors
///
IEnumerable Interceptors { get; }
///
/// Calls all matching interceptors with the specified expression
///
Task> Handle(Expression>>> intercept);
///
/// Calls all matching interceptors with the specified expression
///
Task Handle(Expression> intercept);
}
}