Skip to content

Instantly share code, notes, and snippets.

@activebiz
Last active February 5, 2020 12:35
Show Gist options
  • Save activebiz/f23fd27e1e6fad6f0789d9bb28686428 to your computer and use it in GitHub Desktop.
Save activebiz/f23fd27e1e6fad6f0789d9bb28686428 to your computer and use it in GitHub Desktop.
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