-
Notifications
You must be signed in to change notification settings - Fork 493
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add Validating Directives #583
Merged
pavelnikolov
merged 1 commit into
graph-gophers:master
from
dackroyd:add-validating-directives
Feb 23, 2023
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,13 +5,15 @@ import ( | |
"encoding/json" | ||
"errors" | ||
"fmt" | ||
"strings" | ||
"sync" | ||
"testing" | ||
"time" | ||
|
||
"github.com/graph-gophers/graphql-go" | ||
"github.com/graph-gophers/graphql-go/directives" | ||
gqlerrors "github.com/graph-gophers/graphql-go/errors" | ||
"github.com/graph-gophers/graphql-go/example/social" | ||
"github.com/graph-gophers/graphql-go/example/starwars" | ||
"github.com/graph-gophers/graphql-go/gqltesting" | ||
"github.com/graph-gophers/graphql-go/introspection" | ||
|
@@ -477,6 +479,205 @@ func TestCustomDirective(t *testing.T) { | |
}) | ||
} | ||
|
||
func TestCustomValidatingDirective(t *testing.T) { | ||
t.Parallel() | ||
|
||
gqltesting.RunTests(t, []*gqltesting.Test{ | ||
{ | ||
Schema: graphql.MustParseSchema(` | ||
directive @hasRole(role: String!) on FIELD_DEFINITION | ||
|
||
schema { | ||
query: Query | ||
} | ||
|
||
type Query { | ||
hello: String! @hasRole(role: "ADMIN") | ||
}`, | ||
&helloResolver{}, | ||
graphql.Directives(&HasRoleDirective{}), | ||
), | ||
Context: context.WithValue(context.Background(), RoleKey, "USER"), | ||
Query: ` | ||
{ | ||
hello | ||
} | ||
`, | ||
ExpectedResult: "null", | ||
ExpectedErrors: []*gqlerrors.QueryError{ | ||
{Message: `access denied, role "ADMIN" required`, Locations: []gqlerrors.Location{{Line: 9, Column: 6}}, Path: []interface{}{"hello"}}, | ||
}, | ||
}, | ||
{ | ||
Schema: graphql.MustParseSchema(` | ||
directive @hasRole(role: String!) on FIELD_DEFINITION | ||
|
||
schema { | ||
query: Query | ||
} | ||
|
||
type Query { | ||
hello: String! @hasRole(role: "ADMIN") | ||
}`, | ||
&helloResolver{}, | ||
graphql.Directives(&HasRoleDirective{}), | ||
), | ||
Context: context.WithValue(context.Background(), RoleKey, "ADMIN"), | ||
Query: ` | ||
{ | ||
hello | ||
} | ||
`, | ||
ExpectedResult: ` | ||
{ | ||
"hello": "Hello world!" | ||
} | ||
`, | ||
}, | ||
{ | ||
Schema: graphql.MustParseSchema( | ||
`directive @hasRole(role: String!) on FIELD_DEFINITION | ||
|
||
`+strings.ReplaceAll( | ||
social.Schema, | ||
"role: Role!", | ||
`role: Role! @hasRole(role: "ADMIN")`, | ||
), | ||
&social.Resolver{}, | ||
graphql.Directives(&HasRoleDirective{}), | ||
graphql.UseFieldResolvers(), | ||
), | ||
Context: context.WithValue(context.Background(), RoleKey, "ADMIN"), | ||
Query: ` | ||
query { | ||
user(id: "0x01") { | ||
role | ||
... on User { | ||
} | ||
... on Person { | ||
name | ||
} | ||
} | ||
} | ||
`, | ||
ExpectedResult: ` | ||
{ | ||
"user": { | ||
"role": "ADMIN", | ||
"email": "[email protected]", | ||
"name": "Albus Dumbledore" | ||
} | ||
} | ||
`, | ||
}, | ||
{ | ||
Schema: graphql.MustParseSchema( | ||
`directive @hasRole(role: String!) on FIELD_DEFINITION | ||
|
||
`+strings.ReplaceAll( | ||
starwars.Schema, | ||
"hero(episode: Episode = NEWHOPE): Character", | ||
`hero(episode: Episode = NEWHOPE): Character @hasRole(role: "REBELLION")`, | ||
), | ||
&starwars.Resolver{}, | ||
graphql.Directives(&HasRoleDirective{}), | ||
), | ||
Context: context.WithValue(context.Background(), RoleKey, "EMPIRE"), | ||
Query: ` | ||
query HeroesOfTheRebellion($episode: Episode!) { | ||
hero(episode: $episode) { | ||
id name | ||
... on Human { starships { id name } } | ||
... on Droid { primaryFunction } | ||
} | ||
} | ||
`, | ||
Variables: map[string]interface{}{"episode": "NEWHOPE"}, | ||
ExpectedResult: "null", | ||
ExpectedErrors: []*gqlerrors.QueryError{ | ||
{Message: `access denied, role "REBELLION" required`, Locations: []gqlerrors.Location{{Line: 10, Column: 3}}, Path: []interface{}{"hero"}}, | ||
}, | ||
}, | ||
{ | ||
Schema: graphql.MustParseSchema( | ||
`directive @hasRole(role: String!) on FIELD_DEFINITION | ||
|
||
`+strings.ReplaceAll( | ||
starwars.Schema, | ||
"starships: [Starship]", | ||
`starships: [Starship] @hasRole(role: "REBELLION")`, | ||
), | ||
&starwars.Resolver{}, | ||
graphql.Directives(&HasRoleDirective{}), | ||
), | ||
Context: context.WithValue(context.Background(), RoleKey, "EMPIRE"), | ||
Query: ` | ||
query HeroesOfTheRebellion($episode: Episode!) { | ||
hero(episode: $episode) { | ||
id name | ||
... on Human { starships { id name } } | ||
... on Droid { primaryFunction } | ||
} | ||
} | ||
`, | ||
Variables: map[string]interface{}{"episode": "NEWHOPE"}, | ||
ExpectedResult: "null", | ||
ExpectedErrors: []*gqlerrors.QueryError{ | ||
{Message: `access denied, role "REBELLION" required`, Locations: []gqlerrors.Location{{Line: 68, Column: 3}}, Path: []interface{}{"hero", "starships"}}, | ||
}, | ||
}, | ||
{ | ||
Schema: graphql.MustParseSchema( | ||
`directive @restrictImperialUnits on FIELD_DEFINITION | ||
|
||
`+strings.ReplaceAll( | ||
starwars.Schema, | ||
"height(unit: LengthUnit = METER): Float!", | ||
`height(unit: LengthUnit = METER): Float! @restrictImperialUnits`, | ||
), | ||
&starwars.Resolver{}, | ||
graphql.Directives(&restrictImperialUnitsDirective{}), | ||
), | ||
Context: context.WithValue(context.Background(), RoleKey, "REBELLION"), | ||
Query: ` | ||
query HeroesOfTheRebellion($episode: Episode!) { | ||
hero(episode: $episode) { | ||
id name | ||
... on Human { height(unit: FOOT) } | ||
} | ||
} | ||
`, | ||
Variables: map[string]interface{}{"episode": "NEWHOPE"}, | ||
ExpectedResult: "null", | ||
ExpectedErrors: []*gqlerrors.QueryError{ | ||
{Message: `rebels cannot request imperial units`, Locations: []gqlerrors.Location{{Line: 58, Column: 3}}, Path: []interface{}{"hero", "height"}}, | ||
}, | ||
}, | ||
}) | ||
} | ||
|
||
type restrictImperialUnitsDirective struct{} | ||
|
||
func (d *restrictImperialUnitsDirective) ImplementsDirective() string { | ||
return "restrictImperialUnits" | ||
} | ||
|
||
func (d *restrictImperialUnitsDirective) Validate(ctx context.Context, args interface{}) error { | ||
if ctx.Value(RoleKey) == "EMPIRE" { | ||
return nil | ||
} | ||
|
||
v, ok := args.(struct { | ||
Unit string | ||
}) | ||
if ok && v.Unit == "FOOT" { | ||
return fmt.Errorf("rebels cannot request imperial units") | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func TestCustomDirectiveStructFieldResolver(t *testing.T) { | ||
t.Parallel() | ||
|
||
|
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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -54,6 +54,13 @@ func (r *Request) Execute(ctx context.Context, s *resolvable.Schema, op *ast.Ope | |
default: | ||
panic("unknown query operation") | ||
} | ||
|
||
if errs := validateSelections(ctx, sels, nil, s); errs != nil { | ||
r.Errs = errs | ||
out.Write([]byte("null")) | ||
return | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We can add a global short circuit here. If the schema doesn't have any validation directives, then this entire block can be skipped. |
||
|
||
r.execSelections(ctx, sels, nil, s, resolver, &out, op.Type == query.Mutation) | ||
}() | ||
|
||
|
@@ -64,6 +71,11 @@ func (r *Request) Execute(ctx context.Context, s *resolvable.Schema, op *ast.Ope | |
return out.Bytes(), r.Errs | ||
} | ||
|
||
type fieldToValidate struct { | ||
field *selected.SchemaField | ||
sels []selected.Selection | ||
} | ||
|
||
type fieldToExec struct { | ||
field *selected.SchemaField | ||
sels []selected.Selection | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
(nitpick) You could have used schema extension here : )
I'll add examples how to do that soon.