Directives
A directive annotates part of a query, such as @include(if: $withPages) on a
field, and changes how it is executed. The library runs the directives of the
specification itself; custom directives can be declared and validated, and your
resolvers decide what they do. This page adds both to the catalogue; the
complete program is at the end.
Built-in directives
| Directive | Where | Effect |
|---|---|---|
@include(if: Boolean!) | fields, fragment spreads, inline fragments | Keeps the selection only when if is true. |
@skip(if: Boolean!) | fields, fragment spreads, inline fragments | Removes the selection when if is true. |
@deprecated(reason: String) | field definitions, enum values | Marks part of the schema as deprecated. |
@include and @skip are usually driven by variables, so one document serves
several cases:
query ($withPages: Boolean!) {
book { title pages @include(if: $withPages) }
}A field with both is kept only if @include is true and @skip is false.
A removed field is absent from the response, not null, and its resolver does
not run.
@deprecated belongs to the schema rather than to queries. In Go code it is the
DeprecationReason of a field or enum value, which introspection reports; see
Objects and fields and
Enums.
Declaring a directive
graphql.NewDirective declares a directive with its locations and arguments:
var truncateDirective = graphql.NewDirective(graphql.DirectiveConfig{
Name: "truncate",
Description: "Cuts a string field to at most length characters.",
Locations: []string{graphql.DirectiveLocationField},
Args: graphql.FieldConfigArgument{
"length": &graphql.ArgumentConfig{Type: graphql.NewNonNull(graphql.Int)},
},
})The schema lists it in Directives. That list replaces the built-in one rather
than adding to it, so include graphql.SpecifiedDirectives:
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: queryType,
Directives: append(graphql.SpecifiedDirectives, truncateDirective),
})Without it, @include and @skip stop working: Unknown directive "skip".
Validation then checks every use of the directive against its declaration:
Unknown directive "upper".
Directive "truncate" may not be used on QUERY.
Directive "@truncate" argument "length" of type "Int!" is required but not provided.
Argument "length" has invalid value "5".
Expected type "Int", found "5".Introspection lists the directive with its locations and arguments, so tools such as GraphiQL offer it.
The DirectiveLocation constants also include schema locations, such as
DirectiveLocationFieldDefinition. A schema built in Go code has no syntax to
attach a directive to a type or field, so these locations only declare the
directive for introspection.
Acting on a custom directive
The executor does not run custom directives: it validates them and leaves them
in the query. A resolver can find them in p.Info.FieldASTs, the AST nodes of
the field being resolved. Their arguments are AST values as written, so the
resolver converts literals itself and looks variables up in
p.Info.VariableValues:
func directiveArgs(p graphql.ResolveParams, name string) (map[string]interface{}, bool) {
for _, field := range p.Info.FieldASTs {
for _, d := range field.Directives {
if d.Name.Value != name {
continue
}
args := map[string]interface{}{}
for _, arg := range d.Arguments {
switch v := arg.Value.(type) {
case *ast.Variable:
args[arg.Name.Value] = p.Info.VariableValues[v.Name.Value]
case *ast.IntValue:
n, err := strconv.Atoi(v.Value)
if err != nil {
return nil, false
}
args[arg.Name.Value] = n
default:
args[arg.Name.Value] = v.GetValue()
}
}
return args, true
}
}
return nil, false
}*ast.IntValue holds the digits as a string, hence the conversion. The helper
covers the Int, String and Boolean arguments this example uses; other
types need their own cases.
This works for directives on fields. A directive on a fragment spread or inline fragment is not on the field’s AST node, so a resolver does not see it.
A field selected more than once keeps or drops each selection on its own, so
p.Info.FieldASTs holds only the selections the request includes. Releases
v0.9.0 to v0.12.0 applied only the first selection’s @include or @skip,
which could drop a field or pass excluded selections to the resolver; this is
fixed in v0.12.1 (#107).
Running custom directives in the executor, through field middleware, is on the roadmap (#12, #13).
Current limitations
- Types used only by a directive. The schema does not collect the types of
directive arguments, so a type that no field or argument uses is unknown, and a
variable of that type fails with
Unknown type "Int".(#105). Literals still work. Until it is fixed, list such types inSchemaConfig.Types, for exampleTypes: []graphql.Type{graphql.Int}. The example does not need this, becauseBook.pagesalready usesInt. - Repeated directives. A directive can be used twice in the same place, and the resolver sees both, although the specification allows that only for directives declared repeatable (#24).
Complete program
main.go
package main
import (
"encoding/json"
"fmt"
"log"
"strconv"
"github.com/gql-go/graphql"
"github.com/gql-go/graphql/language/ast"
)
type Book struct {
Title string `json:"title"`
Pages int `json:"pages"`
}
var book = &Book{Title: "The Left Hand of Darkness", Pages: 286}
// truncateDirective asks for a string field to be cut to a maximum length.
var truncateDirective = graphql.NewDirective(graphql.DirectiveConfig{
Name: "truncate",
Description: "Cuts a string field to at most length characters.",
Locations: []string{graphql.DirectiveLocationField},
Args: graphql.FieldConfigArgument{
"length": &graphql.ArgumentConfig{Type: graphql.NewNonNull(graphql.Int)},
},
})
// directiveArgs returns the arguments of the named directive on the field being
// resolved, with variables replaced by their values. It handles the argument
// types this program uses: Int, String and Boolean.
func directiveArgs(p graphql.ResolveParams, name string) (map[string]interface{}, bool) {
for _, field := range p.Info.FieldASTs {
for _, d := range field.Directives {
if d.Name.Value != name {
continue
}
args := map[string]interface{}{}
for _, arg := range d.Arguments {
switch v := arg.Value.(type) {
case *ast.Variable:
args[arg.Name.Value] = p.Info.VariableValues[v.Name.Value]
case *ast.IntValue:
n, err := strconv.Atoi(v.Value)
if err != nil {
return nil, false
}
args[arg.Name.Value] = n
default:
args[arg.Name.Value] = v.GetValue()
}
}
return args, true
}
}
return nil, false
}
func newSchema() (graphql.Schema, error) {
bookType := graphql.NewObject(graphql.ObjectConfig{
Name: "Book",
Fields: graphql.Fields{
"title": &graphql.Field{
Type: graphql.NewNonNull(graphql.String),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
title := p.Source.(*Book).Title
if args, ok := directiveArgs(p, "truncate"); ok {
if n, ok := args["length"].(int); ok && n >= 0 {
if runes := []rune(title); n < len(runes) {
title = string(runes[:n])
}
}
}
return title, nil
},
},
"pages": &graphql.Field{Type: graphql.Int},
},
})
queryType := graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"book": &graphql.Field{
Type: bookType,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return book, nil
},
},
},
})
return graphql.NewSchema(graphql.SchemaConfig{
Query: queryType,
// Directives replaces the built-in list, so it must include it.
Directives: append(graphql.SpecifiedDirectives, truncateDirective),
})
}
func main() {
schema, err := newSchema()
if err != nil {
log.Fatal(err)
}
query := `query ($withPages: Boolean!, $short: Int!) {
full: book { title pages @include(if: $withPages) }
short: book { title @truncate(length: $short) }
shorter: book { title @truncate(length: 3) pages @skip(if: true) }
}`
result := graphql.Do(graphql.Params{
Schema: schema,
RequestString: query,
VariableValues: map[string]interface{}{"withPages": false, "short": 8},
})
out, _ := json.MarshalIndent(result, "", " ")
fmt.Println(string(out))
}full, short and shorter are aliases of the same field with different
directives. $withPages is false, so pages is left out of full. Running
the program prints:
{
"data": {
"full": {
"title": "The Left Hand of Darkness"
},
"short": {
"title": "The Left"
},
"shorter": {
"title": "The"
}
}
}