Skip to content

Commit 477a8d8

Browse files
authored
fix: Nullable arguments in directives (#615)
A query with nullable directives would panic because the library would try to deserialize a null value. This fix adds a null check and skips arguments which have not been supplied. Closes #611
1 parent 224841f commit 477a8d8

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

example_directives_test.go

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,19 @@ func (h *HasRoleDirective) Validate(ctx context.Context, _ interface{}) error {
3030
return nil
3131
}
3232

33+
// NullableDirective
34+
type WithNullableArgumentDirective struct {
35+
ANullableArgument *string
36+
}
37+
38+
func (_ *WithNullableArgumentDirective) Validate(_ context.Context, _ interface{}) error {
39+
return nil
40+
}
41+
42+
func (_ *WithNullableArgumentDirective) ImplementsDirective() string {
43+
return "withNullableArgument"
44+
}
45+
3346
type UpperDirective struct{}
3447

3548
func (d *UpperDirective) ImplementsDirective() string {
@@ -55,6 +68,9 @@ type authResolver struct{}
5568
func (*authResolver) Greet(ctx context.Context, args struct{ Name string }) string {
5669
return fmt.Sprintf("Hello, %s!", args.Name)
5770
}
71+
func (*authResolver) NullableDirective() string {
72+
return "nullableDirective"
73+
}
5874

5975
// ExampleDirectives demonstrates the use of the Directives schema option.
6076
func ExampleDirectives() {
@@ -65,13 +81,15 @@ func ExampleDirectives() {
6581
6682
directive @hasRole(role: String!) on FIELD_DEFINITION
6783
directive @upper on FIELD_DEFINITION
84+
directive @withNullableArgument(aNullableArgument: String) on FIELD_DEFINITION
6885
6986
type Query {
7087
greet(name: String!): String! @hasRole(role: "admin") @upper
88+
nullableDirective: String! @withNullableArgument()
7189
}
7290
`
7391
opts := []graphql.SchemaOpt{
74-
graphql.Directives(&HasRoleDirective{}, &UpperDirective{}),
92+
graphql.Directives(&HasRoleDirective{}, &UpperDirective{}, &WithNullableArgumentDirective{}),
7593
// other options go here
7694
}
7795
schema := graphql.MustParseSchema(s, &authResolver{}, opts...)
@@ -111,7 +129,7 @@ func ExampleDirectives() {
111129
// "message": "access denied, role \"admin\" required",
112130
// "locations": [
113131
// {
114-
// "line": 10,
132+
// "line": 11,
115133
// "column": 4
116134
// }
117135
// ],

internal/exec/resolvable/resolvable.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -650,6 +650,9 @@ func packDirectives(ds ast.DirectiveList, packers map[string]*packer.StructPacke
650650

651651
args := make(map[string]interface{})
652652
for _, arg := range d.Arguments {
653+
if arg.Value == nil {
654+
continue
655+
}
653656
args[arg.Name.Name] = arg.Value.Deserialize(nil)
654657
}
655658

0 commit comments

Comments
 (0)