Skip to content

Commit

Permalink
Added support of custom directives
Browse files Browse the repository at this point in the history
  • Loading branch information
eko committed Dec 28, 2021
1 parent 9d31459 commit a030af0
Show file tree
Hide file tree
Showing 8 changed files with 159 additions and 20 deletions.
5 changes: 3 additions & 2 deletions example/caching/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/graph-gophers/graphql-go"
"github.com/graph-gophers/graphql-go/example/caching"
"github.com/graph-gophers/graphql-go/example/caching/cache"
"github.com/graph-gophers/graphql-go/types"
)

var schema *graphql.Schema
Expand Down Expand Up @@ -40,12 +41,12 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var hint *cache.Hint
if cacheable(r) {
ctx, hints, done := cache.Hintable(r.Context())
response = h.Schema.Exec(ctx, p.Query, p.OperationName, p.Variables)
response = h.Schema.Exec(ctx, p.Query, p.OperationName, p.Variables, map[string]types.DirectiveVisitor{})
done()
v := <-hints
hint = &v
} else {
response = h.Schema.Exec(r.Context(), p.Query, p.OperationName, p.Variables)
response = h.Schema.Exec(r.Context(), p.Query, p.OperationName, p.Variables, map[string]types.DirectiveVisitor{})
}
responseJSON, err := json.Marshal(response)
if err != nil {
Expand Down
20 changes: 11 additions & 9 deletions gqltesting/testing.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,20 @@ import (

graphql "github.com/graph-gophers/graphql-go"
"github.com/graph-gophers/graphql-go/errors"
"github.com/graph-gophers/graphql-go/types"
)

// Test is a GraphQL test case to be used with RunTest(s).
type Test struct {
Context context.Context
Schema *graphql.Schema
Query string
OperationName string
Variables map[string]interface{}
ExpectedResult string
ExpectedErrors []*errors.QueryError
RawResponse bool
Context context.Context
Schema *graphql.Schema
Query string
OperationName string
Variables map[string]interface{}
ExpectedResult string
ExpectedErrors []*errors.QueryError
RawResponse bool
DirectiveVisitors map[string]types.DirectiveVisitor
}

// RunTests runs the given GraphQL test cases as subtests.
Expand All @@ -45,7 +47,7 @@ func RunTest(t *testing.T, test *Test) {
if test.Context == nil {
test.Context = context.Background()
}
result := test.Schema.Exec(test.Context, test.Query, test.OperationName, test.Variables)
result := test.Schema.Exec(test.Context, test.Query, test.OperationName, test.Variables, test.DirectiveVisitors)

checkErrors(t, test.ExpectedErrors, result.Errors)

Expand Down
7 changes: 4 additions & 3 deletions graphql.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,14 +195,14 @@ func (s *Schema) ValidateWithVariables(queryString string, variables map[string]
// Exec executes the given query with the schema's resolver. It panics if the schema was created
// without a resolver. If the context get cancelled, no further resolvers will be called and a
// the context error will be returned as soon as possible (not immediately).
func (s *Schema) Exec(ctx context.Context, queryString string, operationName string, variables map[string]interface{}) *Response {
func (s *Schema) Exec(ctx context.Context, queryString string, operationName string, variables map[string]interface{}, visitors map[string]types.DirectiveVisitor) *Response {
if !s.res.Resolver.IsValid() {
panic("schema created without resolver, can not exec")
}
return s.exec(ctx, queryString, operationName, variables, s.res)
return s.exec(ctx, queryString, operationName, variables, visitors, s.res)
}

func (s *Schema) exec(ctx context.Context, queryString string, operationName string, variables map[string]interface{}, res *resolvable.Schema) *Response {
func (s *Schema) exec(ctx context.Context, queryString string, operationName string, variables map[string]interface{}, visitors map[string]types.DirectiveVisitor, res *resolvable.Schema) *Response {
doc, qErr := query.Parse(queryString)
if qErr != nil {
return &Response{Errors: []*errors.QueryError{qErr}}
Expand Down Expand Up @@ -257,6 +257,7 @@ func (s *Schema) exec(ctx context.Context, queryString string, operationName str
Tracer: s.tracer,
Logger: s.logger,
PanicHandler: s.panicHandler,
Visitors: visitors,
}
varTypes := make(map[string]*introspection.Type)
for _, v := range op.Vars {
Expand Down
90 changes: 87 additions & 3 deletions graphql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"github.com/graph-gophers/graphql-go/gqltesting"
"github.com/graph-gophers/graphql-go/introspection"
"github.com/graph-gophers/graphql-go/trace"
"github.com/graph-gophers/graphql-go/types"
)

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

type customDirectiveVisitor struct {
beforeWasCalled bool
}

func (v *customDirectiveVisitor) Before(ctx context.Context, directive *types.Directive, input interface{}) error {
v.beforeWasCalled = true
return nil
}

func (v *customDirectiveVisitor) After(ctx context.Context, directive *types.Directive, output interface{}) (interface{}, error) {
if v.beforeWasCalled == false {
return nil, errors.New("Before directive visitor method wasn't called.")
}

if value, ok := directive.Arguments.Get("customAttribute"); ok {
return fmt.Sprintf("Directive '%s' (with arg '%s') modified result: %s", directive.Name.Name, value.String(), output.(string)), nil
} else {
return fmt.Sprintf("Directive '%s' modified result: %s", directive.Name.Name, output.(string)), nil
}
}

type theNumberResolver struct {
number int32
}
Expand Down Expand Up @@ -191,7 +213,6 @@ func TestHelloWorld(t *testing.T) {
}
`,
},

{
Schema: graphql.MustParseSchema(`
schema {
Expand All @@ -216,6 +237,67 @@ func TestHelloWorld(t *testing.T) {
})
}

func TestCustomDirective(t *testing.T) {
t.Parallel()

gqltesting.RunTests(t, []*gqltesting.Test{
{
Schema: graphql.MustParseSchema(`
directive @customDirective on FIELD_DEFINITION
schema {
query: Query
}
type Query {
hello_html: String! @customDirective
}
`, &helloSnakeResolver1{}),
Query: `
{
hello_html
}
`,
ExpectedResult: `
{
"hello_html": "Directive 'customDirective' modified result: Hello snake!"
}
`,
DirectiveVisitors: map[string]types.DirectiveVisitor{
"customDirective": &customDirectiveVisitor{},
},
},
{
Schema: graphql.MustParseSchema(`
directive @customDirective(
customAttribute: String!
) on FIELD_DEFINITION
schema {
query: Query
}
type Query {
say_hello(full_name: String!): String! @customDirective(customAttribute: hi)
}
`, &helloSnakeResolver1{}),
Query: `
{
say_hello(full_name: "Johnny")
}
`,
ExpectedResult: `
{
"say_hello": "Directive 'customDirective' (with arg 'hi') modified result: Hello Johnny!"
}
`,
DirectiveVisitors: map[string]types.DirectiveVisitor{
"customDirective": &customDirectiveVisitor{},
},
},
})
}

func TestHelloSnake(t *testing.T) {
t.Parallel()

Expand Down Expand Up @@ -3757,7 +3839,7 @@ func TestSchema_Exec_without_resolver(t *testing.T) {
t.Fail()
}
}()
_ = s.Exec(context.Background(), tt.Args.Query, "", map[string]interface{}{})
_ = s.Exec(context.Background(), tt.Args.Query, "", map[string]interface{}{}, map[string]types.DirectiveVisitor{})
})
}
}
Expand Down Expand Up @@ -4113,7 +4195,9 @@ func TestTracer(t *testing.T) {
"id": "1002",
}

_ = schema.Exec(ctx, doc, opName, variables)
visitors := map[string]types.DirectiveVisitor{}

_ = schema.Exec(ctx, doc, opName, variables, visitors)

tracer.mu.Lock()
defer tracer.mu.Unlock()
Expand Down
40 changes: 40 additions & 0 deletions internal/exec/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ type Request struct {
Logger log.Logger
PanicHandler errors.PanicHandler
SubscribeResolverTimeout time.Duration
Visitors map[string]types.DirectiveVisitor
}

func (r *Request) handlePanic(ctx context.Context) {
Expand Down Expand Up @@ -208,8 +209,47 @@ func execFieldSelection(ctx context.Context, r *Request, s *resolvable.Schema, f
if f.field.ArgsPacker != nil {
in = append(in, f.field.PackedArgs)
}

// Before hook directive visitor
if len(f.field.Directives) > 0 {
for _, directive := range f.field.Directives {
if visitor, ok := r.Visitors[directive.Name.Name]; ok {
var values = make([]interface{}, 0)
for _, inValue := range in {
values = append(values, inValue.Interface())
}

if visitorErr := visitor.Before(ctx, directive, values); err != nil {
err := errors.Errorf("%s", visitorErr)
err.Path = path.toSlice()
err.ResolverError = visitorErr
return err
}
}
}
}

// Call method
callOut := res.Method(f.field.MethodIndex).Call(in)
result = callOut[0]

// After hook directive visitor (when no error is returned from resolver)
if !f.field.HasError && len(f.field.Directives) > 0 {
for _, directive := range f.field.Directives {
if visitor, ok := r.Visitors[directive.Name.Name]; ok {
returned, visitorErr := visitor.After(ctx, directive, result.Interface())
if err != nil {
err := errors.Errorf("%s", visitorErr)
err.Path = path.toSlice()
err.ResolverError = visitorErr
return err
} else {
result = reflect.ValueOf(returned)
}
}
}
}

if f.field.HasError && !callOut[1].IsNil() {
resolverErr := callOut[1].Interface().(error)
err := errors.Errorf("%s", resolverErr)
Expand Down
3 changes: 2 additions & 1 deletion introspection.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (

"github.com/graph-gophers/graphql-go/internal/exec/resolvable"
"github.com/graph-gophers/graphql-go/introspection"
"github.com/graph-gophers/graphql-go/types"
)

// Inspect allows inspection of the given schema.
Expand All @@ -15,7 +16,7 @@ func (s *Schema) Inspect() *introspection.Schema {

// ToJSON encodes the schema in a JSON format used by tools like Relay.
func (s *Schema) ToJSON() ([]byte, error) {
result := s.exec(context.Background(), introspectionQuery, "", nil, &resolvable.Schema{
result := s.exec(context.Background(), introspectionQuery, "", nil, map[string]types.DirectiveVisitor{}, &resolvable.Schema{
Meta: s.res.Meta,
Query: &resolvable.Object{},
Schema: *s.schema,
Expand Down
3 changes: 2 additions & 1 deletion relay/relay.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"strings"

graphql "github.com/graph-gophers/graphql-go"
"github.com/graph-gophers/graphql-go/types"
)

func MarshalID(kind string, spec interface{}) graphql.ID {
Expand Down Expand Up @@ -58,7 +59,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}

response := h.Schema.Exec(r.Context(), params.Query, params.OperationName, params.Variables)
response := h.Schema.Exec(r.Context(), params.Query, params.OperationName, params.Variables, map[string]types.DirectiveVisitor{})
responseJSON, err := json.Marshal(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
Expand Down
11 changes: 10 additions & 1 deletion types/directive.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package types

import "github.com/graph-gophers/graphql-go/errors"
import (
"context"

"github.com/graph-gophers/graphql-go/errors"
)

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

type DirectiveList []*Directive

type DirectiveVisitor interface {
Before(ctx context.Context, directive *Directive, input interface{}) error
After(ctx context.Context, directive *Directive, output interface{}) (interface{}, error)
}

// Returns the Directive in the DirectiveList by name or nil if not found.
func (l DirectiveList) Get(name string) *Directive {
for _, d := range l {
Expand Down

0 comments on commit a030af0

Please sign in to comment.