Last active
February 23, 2022 06:19
-
-
Save umayeras/36ca9bcdd1b62ae675aafaf964f4628a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> | |
where TRequest : IRequest<TResponse> | |
where TResponse : ServiceResponse, new() | |
{ | |
private readonly IEnumerable<IValidator<TRequest>> validators; | |
public ValidationBehavior(IEnumerable<IValidator<TRequest>> validators) | |
{ | |
this.validators = validators; | |
} | |
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next) | |
{ | |
if (!validators.Any()) | |
{ | |
return await next.Invoke(); | |
} | |
var context = new ValidationContext<TRequest>(request); | |
var results = await Task.WhenAll(validators.Select(v => v.ValidateAsync(context, cancellationToken))); | |
var failures = results.SelectMany(r => r.Errors).Where(f => f != null).ToList(); | |
if (!failures.Any()) | |
{ | |
return await next.Invoke(); | |
} | |
var response = CreateValidationErrorResponse(failures); | |
return await Task.FromResult(response as TResponse); | |
} | |
private ValidationErrorResponse CreateValidationErrorResponse(IEnumerable<ValidationFailure> failures) | |
{ | |
var errors = failures.Select(failure => new ValidationError(failure.PropertyName, failure.ErrorMessage)).ToList(); | |
return ValidationErrorResponse.Create(errors); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment