Skip to content

Commit 8eb238d

Browse files
committed
Added support of custom directives
1 parent 9d31459 commit 8eb238d

File tree

4 files changed

+143
-2
lines changed

4 files changed

+143
-2
lines changed

graphql.go

+10
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ type Schema struct {
8282
useStringDescriptions bool
8383
disableIntrospection bool
8484
subscribeResolverTimeout time.Duration
85+
visitors map[string]types.DirectiveVisitor
8586
}
8687

8788
func (s *Schema) ASTSchema() *types.Schema {
@@ -168,6 +169,14 @@ func SubscribeResolverTimeout(timeout time.Duration) SchemaOpt {
168169
}
169170
}
170171

172+
// DirectiveVisitors allows to pass custom directive visitors that will be able to handle
173+
// you GraphQL schema directives.
174+
func DirectiveVisitors(visitors map[string]types.DirectiveVisitor) SchemaOpt {
175+
return func(s *Schema) {
176+
s.visitors = visitors
177+
}
178+
}
179+
171180
// Response represents a typical response of a GraphQL server. It may be encoded to JSON directly or
172181
// it may be further processed to a custom response type, for example to include custom error data.
173182
// Errors are intentionally serialized first based on the advice in https://github.com/facebook/graphql/commit/7b40390d48680b15cb93e02d46ac5eb249689876#diff-757cea6edf0288677a9eea4cfc801d87R107
@@ -257,6 +266,7 @@ func (s *Schema) exec(ctx context.Context, queryString string, operationName str
257266
Tracer: s.tracer,
258267
Logger: s.logger,
259268
PanicHandler: s.panicHandler,
269+
Visitors: s.visitors,
260270
}
261271
varTypes := make(map[string]*introspection.Type)
262272
for _, v := range op.Vars {

graphql_test.go

+83-1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import (
1414
"github.com/graph-gophers/graphql-go/gqltesting"
1515
"github.com/graph-gophers/graphql-go/introspection"
1616
"github.com/graph-gophers/graphql-go/trace"
17+
"github.com/graph-gophers/graphql-go/types"
1718
)
1819

1920
type helloWorldResolver1 struct{}
@@ -48,6 +49,27 @@ func (r *helloSnakeResolver2) SayHello(ctx context.Context, args struct{ FullNam
4849
return "Hello " + args.FullName + "!", nil
4950
}
5051

52+
type customDirectiveVisitor struct {
53+
beforeWasCalled bool
54+
}
55+
56+
func (v *customDirectiveVisitor) Before(ctx context.Context, directive *types.Directive, input interface{}) error {
57+
v.beforeWasCalled = true
58+
return nil
59+
}
60+
61+
func (v *customDirectiveVisitor) After(ctx context.Context, directive *types.Directive, output interface{}) (interface{}, error) {
62+
if v.beforeWasCalled == false {
63+
return nil, errors.New("Before directive visitor method wasn't called.")
64+
}
65+
66+
if value, ok := directive.Arguments.Get("customAttribute"); ok {
67+
return fmt.Sprintf("Directive '%s' (with arg '%s') modified result: %s", directive.Name.Name, value.String(), output.(string)), nil
68+
} else {
69+
return fmt.Sprintf("Directive '%s' modified result: %s", directive.Name.Name, output.(string)), nil
70+
}
71+
}
72+
5173
type theNumberResolver struct {
5274
number int32
5375
}
@@ -191,7 +213,6 @@ func TestHelloWorld(t *testing.T) {
191213
}
192214
`,
193215
},
194-
195216
{
196217
Schema: graphql.MustParseSchema(`
197218
schema {
@@ -216,6 +237,67 @@ func TestHelloWorld(t *testing.T) {
216237
})
217238
}
218239

240+
func TestCustomDirective(t *testing.T) {
241+
t.Parallel()
242+
243+
gqltesting.RunTests(t, []*gqltesting.Test{
244+
{
245+
Schema: graphql.MustParseSchema(`
246+
directive @customDirective on FIELD_DEFINITION
247+
248+
schema {
249+
query: Query
250+
}
251+
252+
type Query {
253+
hello_html: String! @customDirective
254+
}
255+
`, &helloSnakeResolver1{},
256+
graphql.DirectiveVisitors(map[string]types.DirectiveVisitor{
257+
"customDirective": &customDirectiveVisitor{},
258+
})),
259+
Query: `
260+
{
261+
hello_html
262+
}
263+
`,
264+
ExpectedResult: `
265+
{
266+
"hello_html": "Directive 'customDirective' modified result: Hello snake!"
267+
}
268+
`,
269+
},
270+
{
271+
Schema: graphql.MustParseSchema(`
272+
directive @customDirective(
273+
customAttribute: String!
274+
) on FIELD_DEFINITION
275+
276+
schema {
277+
query: Query
278+
}
279+
280+
type Query {
281+
say_hello(full_name: String!): String! @customDirective(customAttribute: hi)
282+
}
283+
`, &helloSnakeResolver1{},
284+
graphql.DirectiveVisitors(map[string]types.DirectiveVisitor{
285+
"customDirective": &customDirectiveVisitor{},
286+
})),
287+
Query: `
288+
{
289+
say_hello(full_name: "Johnny")
290+
}
291+
`,
292+
ExpectedResult: `
293+
{
294+
"say_hello": "Directive 'customDirective' (with arg 'hi') modified result: Hello Johnny!"
295+
}
296+
`,
297+
},
298+
})
299+
}
300+
219301
func TestHelloSnake(t *testing.T) {
220302
t.Parallel()
221303

internal/exec/exec.go

+40
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ type Request struct {
2525
Logger log.Logger
2626
PanicHandler errors.PanicHandler
2727
SubscribeResolverTimeout time.Duration
28+
Visitors map[string]types.DirectiveVisitor
2829
}
2930

3031
func (r *Request) handlePanic(ctx context.Context) {
@@ -208,8 +209,47 @@ func execFieldSelection(ctx context.Context, r *Request, s *resolvable.Schema, f
208209
if f.field.ArgsPacker != nil {
209210
in = append(in, f.field.PackedArgs)
210211
}
212+
213+
// Before hook directive visitor
214+
if len(f.field.Directives) > 0 {
215+
for _, directive := range f.field.Directives {
216+
if visitor, ok := r.Visitors[directive.Name.Name]; ok {
217+
var values = make([]interface{}, 0)
218+
for _, inValue := range in {
219+
values = append(values, inValue.Interface())
220+
}
221+
222+
if visitorErr := visitor.Before(ctx, directive, values); err != nil {
223+
err := errors.Errorf("%s", visitorErr)
224+
err.Path = path.toSlice()
225+
err.ResolverError = visitorErr
226+
return err
227+
}
228+
}
229+
}
230+
}
231+
232+
// Call method
211233
callOut := res.Method(f.field.MethodIndex).Call(in)
212234
result = callOut[0]
235+
236+
// After hook directive visitor (when no error is returned from resolver)
237+
if !f.field.HasError && len(f.field.Directives) > 0 {
238+
for _, directive := range f.field.Directives {
239+
if visitor, ok := r.Visitors[directive.Name.Name]; ok {
240+
returned, visitorErr := visitor.After(ctx, directive, result.Interface())
241+
if err != nil {
242+
err := errors.Errorf("%s", visitorErr)
243+
err.Path = path.toSlice()
244+
err.ResolverError = visitorErr
245+
return err
246+
} else {
247+
result = reflect.ValueOf(returned)
248+
}
249+
}
250+
}
251+
}
252+
213253
if f.field.HasError && !callOut[1].IsNil() {
214254
resolverErr := callOut[1].Interface().(error)
215255
err := errors.Errorf("%s", resolverErr)

types/directive.go

+10-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
package types
22

3-
import "github.com/graph-gophers/graphql-go/errors"
3+
import (
4+
"context"
5+
6+
"github.com/graph-gophers/graphql-go/errors"
7+
)
48

59
// Directive is a representation of the GraphQL Directive.
610
//
@@ -23,6 +27,11 @@ type DirectiveDefinition struct {
2327

2428
type DirectiveList []*Directive
2529

30+
type DirectiveVisitor interface {
31+
Before(ctx context.Context, directive *Directive, input interface{}) error
32+
After(ctx context.Context, directive *Directive, output interface{}) (interface{}, error)
33+
}
34+
2635
// Returns the Directive in the DirectiveList by name or nil if not found.
2736
func (l DirectiveList) Get(name string) *Directive {
2837
for _, d := range l {

0 commit comments

Comments
 (0)