#region ========================================================================= USING =====================================================================================
using Mediator;
using ErrorOr;
using FluentValidation;
#endregion
namespace Lumina.Application.Common.Behaviors;
///
/// Behavior pipeline for the register command
///
/// The type representing a request. It should implement .
/// The type representing a response. It should implement interface.
public class ValidationBehavior : IPipelineBehavior where TRequest : IRequest
where TResponse : IErrorOr
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IValidator? validator;
#endregion
#region ====================================================================== CTOR =====================================================================================
///
/// Initializes a new instance of the class.
///
/// The validator used in this behavior pipeline for the Mediator commands and queries.
public ValidationBehavior(IValidator? validator = null)
{
this.validator = validator;
}
#endregion
#region ===================================================================== METHODS ===================================================================================
///
/// Pipeline handler. Perform any additional behavior and await the delegate as necessary.
///
/// Incoming request.
/// Awaitable delegate for the next action in the pipeline. Eventually this delegate represents the handler.
/// Cancellation token.
public async ValueTask Handle(TRequest request, CancellationToken cancellationToken, MessageHandlerDelegate next)
{
// if there is no validator, just invoke the handler
if (validator is null)
return await next(request, cancellationToken);
// before the handler of the command is executed
var validationResult = await validator.ValidateAsync(request, cancellationToken);
// if there are no validation errors, invoke the command handler
if (validationResult.IsValid)
return await next(request, cancellationToken);
// after the command handler is executed
var errors = validationResult.Errors.ConvertAll(validationFailure => Error.Validation(validationFailure.ErrorMessage));
// the compiler doesn't know there is an implicit converter from a list of errors to the ErrorOr object, and unfortunately, there is no way around this but to use some magic
// this is acceptable because we DO know that we will always have a list of errors of type ErrorOr (check the generic constraint at the top of the class!)
return (dynamic)errors;
}
#endregion
}