Skip to content

Commit

Permalink
Merge pull request #4 from svelue/addServiceProviderToValidationContext
Browse files Browse the repository at this point in the history
Add service provider to validation context
  • Loading branch information
VarunSaiTeja authored Dec 3, 2021
2 parents a8b5706 + e294ff3 commit 9d8ced7
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/ValidationMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public async Task InvokeAsync(IMiddlewareContext context)
value is Validate validate)
{
var input = context.ArgumentValue<object>(argument.Name);
var validationContext = new ValidationContext(input);
var validationContext = new ValidationContext(input, context.Services, null);
validate(input, validationContext, errors);

if (errors.Any())
Expand Down
21 changes: 20 additions & 1 deletion test/ValidationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public async Task Ensure_Validation_Works_On_Arguments()
{
var result =
await new ServiceCollection()
.AddScoped(_ => new Service())
.AddGraphQL()
.AddQueryType<Query>()
.AddArgumentValidator()
Expand All @@ -28,6 +29,7 @@ public async Task Ensure_Validation_Works_On_Arguments_ValidEmail()
{
var result =
await new ServiceCollection()
.AddScoped(_ => new Service())
.AddGraphQL()
.AddQueryType<Query>()
.AddArgumentValidator()
Expand All @@ -41,6 +43,7 @@ public async Task Ensure_Validation_Works_On_InputObjects()
{
var result =
await new ServiceCollection()
.AddScoped(_ => new Service())
.AddGraphQL()
.AddQueryType<Query>()
.AddArgumentValidator()
Expand All @@ -54,6 +57,7 @@ public async Task Ensure_Validation_Works_On_InputObjects_ValidEmail()
{
var result =
await new ServiceCollection()
.AddScoped(_ => new Service())
.AddGraphQL()
.AddQueryType<Query>()
.AddArgumentValidator()
Expand All @@ -65,7 +69,7 @@ public async Task Ensure_Validation_Works_On_InputObjects_ValidEmail()

public class Query
{
public string ArgIsEmail([EmailAddress] string email) => email;
public string ArgIsEmail([EmailAddress][ResolveService] string email) => email;

public string ArgIsInput(MyInput input) => input.Email;
}
Expand All @@ -74,6 +78,21 @@ public class Query
public class MyInput
{
[EmailAddress]
[ResolveService]
public string Email { get; set; }
}

public class Service
{
public bool CouldBeResolved => true;
}

public class ResolveServiceAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var service = (Service)validationContext.GetService(typeof(Service));
return service is { CouldBeResolved: true } ? ValidationResult.Success : new ValidationResult("error");
}
}
}

0 comments on commit 9d8ced7

Please sign in to comment.