| | | 1 | | using FluentValidation; |
| | | 2 | | using Microsoft.Extensions.Logging; |
| | | 3 | | using NexMediator.Abstractions.Interfaces; |
| | | 4 | | |
| | | 5 | | namespace NexMediator.Pipeline.Behaviors; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Pipeline behavior that runs FluentValidation rules on the request. |
| | | 9 | | /// </summary> |
| | | 10 | | /// <typeparam name="TRequest">The request type.</typeparam> |
| | | 11 | | /// <typeparam name="TResponse">The response type.</typeparam> |
| | | 12 | | public class FluentValidationBehavior<TRequest, TResponse> : INexPipelineBehavior<TRequest, TResponse> |
| | | 13 | | where TRequest : INexRequest<TResponse> |
| | | 14 | | { |
| | | 15 | | private readonly IEnumerable<IValidator<TRequest>> _validators; |
| | | 16 | | private readonly ILogger<FluentValidationBehavior<TRequest, TResponse>> _logger; |
| | | 17 | | |
| | | 18 | | /// <summary> |
| | | 19 | | /// Create the validation behavior. |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="validators">A list of validators from DI.</param> |
| | | 22 | | /// <param name="logger">Logger instance for messages.</param> |
| | 6 | 23 | | public FluentValidationBehavior( |
| | 6 | 24 | | IEnumerable<IValidator<TRequest>> validators, |
| | 6 | 25 | | ILogger<FluentValidationBehavior<TRequest, TResponse>> logger) |
| | 6 | 26 | | { |
| | 6 | 27 | | _validators = validators ?? throw new ArgumentNullException(nameof(validators)); |
| | 5 | 28 | | _logger = logger ?? throw new ArgumentNullException(nameof(logger)); |
| | 4 | 29 | | } |
| | | 30 | | |
| | | 31 | | /// <summary> |
| | | 32 | | /// Run all validators for the request. If any errors, throw exception. |
| | | 33 | | /// </summary> |
| | | 34 | | /// <param name="request">The request to validate.</param> |
| | | 35 | | /// <param name="next">Next handler in the pipeline.</param> |
| | | 36 | | /// <param name="cancellationToken">Token to cancel the work.</param> |
| | | 37 | | /// <returns>The response, or throws if request is invalid.</returns> |
| | | 38 | | public async Task<TResponse> Handle( |
| | | 39 | | TRequest request, |
| | | 40 | | RequestHandlerDelegate<TResponse> next, |
| | | 41 | | CancellationToken cancellationToken) |
| | 4 | 42 | | { |
| | | 43 | | // If no validators, skip validation |
| | 5 | 44 | | if (!_validators.Any()) return await next(); |
| | | 45 | | |
| | 3 | 46 | | var context = new ValidationContext<TRequest>(request); |
| | | 47 | | |
| | | 48 | | // Remove duplicated validators (by type) |
| | 3 | 49 | | var distinctValidators = _validators |
| | 4 | 50 | | .Where(v => v.GetType() != typeof(InlineValidator<TRequest>)) |
| | 4 | 51 | | .GroupBy(v => v.GetType()) |
| | 4 | 52 | | .Select(g => g.First()) |
| | 3 | 53 | | .ToList(); |
| | | 54 | | |
| | 3 | 55 | | _logger.LogDebug("Running {ValidatorCount} validators for request {RequestType}", distinctValidators.Count, type |
| | | 56 | | |
| | | 57 | | // Run all validations in parallel |
| | 7 | 58 | | var validationResults = await Task.WhenAll(distinctValidators.Select(v => v.ValidateAsync(context, cancellationT |
| | | 59 | | |
| | | 60 | | // Collect all errors |
| | 10 | 61 | | var failures = validationResults.Where(r => !r.IsValid).SelectMany(r => r.Errors).ToList(); |
| | | 62 | | |
| | | 63 | | // If any validation failed, log and throw |
| | 3 | 64 | | if (failures.Any()) |
| | 2 | 65 | | { |
| | 2 | 66 | | _logger.LogWarning("Validation failed for {RequestType} with {ErrorCount} errors", typeof(TRequest).Name, fa |
| | 2 | 67 | | throw new ValidationException("One or more validation errors occurred.", failures); |
| | | 68 | | } |
| | | 69 | | |
| | | 70 | | // All validations passed |
| | 1 | 71 | | return await next(); |
| | 2 | 72 | | } |
| | | 73 | | } |