Last active
February 5, 2020 12:35
-
-
Save activebiz/f23fd27e1e6fad6f0789d9bb28686428 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 MyValidationMiddleware<T, V> | |
{ | |
private readonly FieldDelegate _next; | |
private readonly IMyValidator<T, V> _validator; | |
public MyValidationMiddleware(FieldDelegate next, IMyValidator<T, V> validator) | |
{ | |
_next = next; | |
_validator = validator; | |
} | |
public async Task InvokeAsync(IMiddlewareContext context) | |
{ | |
var inputs = context.FieldSelection.Arguments | |
.Select(x => context.Argument<T>(x.Name.Value)).ToList(); | |
if (inputs != null && inputs.Count() > 0) | |
{ | |
bool hasError = false; | |
foreach (var input in inputs) | |
{ | |
ValidationResult result = await this._validator.ValidateAsync<T>(input); | |
if (!result.IsValid) | |
{ | |
hasError = true; | |
SetErrorResult(context, result); | |
} | |
} | |
if (hasError) | |
{ | |
return; | |
} | |
} | |
await _next(context); | |
return; | |
} | |
private void SetErrorResult(IMiddlewareContext context, ValidationResult result) | |
{ | |
foreach (var validationError in result.Errors) | |
{ | |
context.ReportError(ErrorBuilder.New() | |
.SetMessage(validationError.ErrorMessage) | |
.SetExtension(validationError.ErrorCode, validationError.AttemptedValue) | |
.SetPath(context.Path) | |
.Build()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment