forked from graph-gophers/graphql-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_directives_test.go
131 lines (114 loc) · 2.51 KB
/
example_directives_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package graphql_test
import (
"context"
"encoding/json"
"fmt"
"os"
"strings"
"github.com/graph-gophers/graphql-go"
"github.com/graph-gophers/graphql-go/directives"
)
type roleKey string
const RoleKey = roleKey("role")
type HasRoleDirective struct {
Role string
}
func (h *HasRoleDirective) ImplementsDirective() string {
return "hasRole"
}
func (h *HasRoleDirective) Validate(ctx context.Context, _ interface{}) error {
if ctx.Value(RoleKey) != h.Role {
return fmt.Errorf("access denied, role %q required", h.Role)
}
return nil
}
type UpperDirective struct{}
func (d *UpperDirective) ImplementsDirective() string {
return "upper"
}
func (d *UpperDirective) Resolve(ctx context.Context, args interface{}, next directives.Resolver) (interface{}, error) {
out, err := next.Resolve(ctx, args)
if err != nil {
return out, err
}
s, ok := out.(string)
if !ok {
return out, nil
}
return strings.ToUpper(s), nil
}
type authResolver struct{}
func (*authResolver) Greet(ctx context.Context, args struct{ Name string }) string {
return fmt.Sprintf("Hello, %s!", args.Name)
}
// ExampleDirectives demonstrates the use of the Directives schema option.
func ExampleDirectives() {
s := `
schema {
query: Query
}
directive @hasRole(role: String!) on FIELD_DEFINITION
directive @upper on FIELD_DEFINITION
type Query {
greet(name: String!): String! @hasRole(role: "admin") @upper
}
`
opts := []graphql.SchemaOpt{
graphql.Directives(&HasRoleDirective{}, &UpperDirective{}),
// other options go here
}
schema := graphql.MustParseSchema(s, &authResolver{}, opts...)
query := `
query {
greet(name: "GraphQL")
}
`
cases := []struct {
name string
ctx context.Context
}{
{
name: "Unauthorized",
ctx: context.Background(),
},
{
name: "Admin user",
ctx: context.WithValue(context.Background(), RoleKey, "admin"),
},
}
for _, c := range cases {
fmt.Println(c.name, "result:")
res := schema.Exec(c.ctx, query, "", nil)
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
err := enc.Encode(res)
if err != nil {
panic(err)
}
}
// output:
// Unauthorized result:
// {
// "errors": [
// {
// "message": "access denied, role \"admin\" required",
// "locations": [
// {
// "line": 10,
// "column": 4
// }
// ],
// "path": [
// "greet"
// ]
// }
// ],
// "data": null
// }
// Admin user result:
// {
// "data": {
// "greet": "HELLO, GRAPHQL!"
// }
// }
}