Files
mixtape/zero.Core/Collections/CollectionInterceptorHandler.cs
T

92 lines
2.3 KiB
C#
Raw Normal View History

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