Language tools
The packages under language/ work on GraphQL documents without executing
them: they parse text into a syntax tree, walk and rewrite the tree, and print
it back as text. They are what the library itself uses, and they serve tools
such as linters, document registries, code generators and query rewriting.
This page shows each one; the complete program combines
them.
| Package | Use |
|---|---|
language/parser | Parses a document, or a single value, into a tree. |
language/ast | The node types of the tree, such as ast.Document, ast.OperationDefinition and ast.Field. |
language/kinds | Names for each kind of node, such as kinds.Field. |
language/source | The text being parsed, with the name used in error messages. |
language/printer | Prints a tree as text. |
language/visitor | Walks a tree, and rewrites it. |
Parsing
parser.Parse takes the document as a string, or as a *source.Source that
also names it:
// parse parses a document, naming it after the file it came from so that
// syntax errors say where they are.
func parse(name, body string) (*ast.Document, error) {
return parser.Parse(parser.ParseParams{
Source: source.NewSource(&source.Source{Body: []byte(body), Name: name}),
})
}A syntax error is a *gqlerrors.Error, whose Locations give the line and
column, and whose message names the source and shows the line:
Syntax Error broken.graphql (1:18) Expected Name, found EOF
1: { books { title }
^Without a name, the message says GraphQL; graphql.Do names its source
GraphQL request.
Each node records where it is in the text in Loc, as byte offsets (Start,
End) and a pointer to the source. A comment that contains a multibyte
character, such as # café, shifts the offsets of everything after it
(#164), so check the text before
slicing the source with them. ParseOptions{NoLocation: true} leaves Loc
out, and NoSource: true keeps the offsets without the source; both save memory
when the positions are not needed.
parser.ParseValue parses a single value, such as {a: [1, "two", $v]}, into an
ast.Value.
The parser also reads the type system language (SDL): type, interface,
schema and the other definitions parse into their own nodes, and print back.
Building a schema from SDL, or printing a schema as SDL, is on the roadmap
(#40).
The tree
ast.Document holds a list of Definitions; each node has a GetKind() method
that returns one of the names in language/kinds, and code usually switches on
the node’s type:
for _, def := range doc.Definitions {
switch def := def.(type) {
case *ast.OperationDefinition:
// def.Operation is "query", "mutation" or "subscription";
// def.SelectionSet holds its fields.
case *ast.FragmentDefinition:
// def.Name.Value, def.TypeCondition, def.SelectionSet
}
}Selections are *ast.Field, *ast.FragmentSpread or *ast.InlineFragment. The
same tree is what resolvers see in p.Info.FieldASTs, and what
validation rules walk.
Printing
printer.Print returns the text of a node, as an interface{} that holds a
string. Printing formats the document in a standard way: two-space
indentation, one selection per line, and no comments, since the parser drops
them:
text := printer.Print(doc).(string)Two known problems: block strings in descriptions can change when printed
(#86), and a node the printer
cannot handle makes Print return nil, which panics the type assertion above
(#162); check it with
s, ok := printer.Print(n).(string) when the tree was built by hand.
Visiting
visitor.Visit walks a tree depth first and calls your functions for the nodes
it enters and leaves. KindFuncMap maps a kind to its functions: Kind or
Enter when the walk enters a node of that kind, Leave when it leaves it.
Enter and Leave on VisitorOptions itself are called for the other nodes:
for a kind listed in KindFuncMap, its own functions replace the generic ones,
even the one it leaves out, so an entry with only Leave means that nodes of
that kind get no Enter call at all.
Each function returns an action:
| Action | Effect |
|---|---|
visitor.ActionNoChange | Go on. |
visitor.ActionSkip | Do not visit this node’s children (on enter). |
visitor.ActionBreak | Stop the walk. |
visitor.ActionUpdate | Replace the node with the returned value; nil removes it. |
Visit returns the tree with the updates applied, or nil when no function
returned ActionUpdate (#165).
After ActionBreak, updates still pending at that point are not applied, and
the result can be nil too. This helper adds __typename where it is missing:
// withTypename adds __typename to every selection set that does not
// already use that response key, so that clients can tell the type of each
// object, as client caches do. Visit edits doc in place (#161), so pass a
// document that nothing else uses.
func withTypename(doc *ast.Document) *ast.Document {
edited := visitor.Visit(doc, &visitor.VisitorOptions{
KindFuncMap: map[string]visitor.NamedVisitFuncs{
kinds.SelectionSet: {
Leave: func(p visitor.VisitFuncParams) (string, interface{}) {
set := p.Node.(*ast.SelectionSet)
for _, sel := range set.Selections {
f, ok := sel.(*ast.Field)
if !ok {
continue
}
// Skip sets that already use the response key,
// even as an alias of another field.
key := f.Name.Value
if f.Alias != nil {
key = f.Alias.Value
}
if key == "__typename" {
return visitor.ActionNoChange, nil
}
}
selections := append(append([]ast.Selection{}, set.Selections...),
ast.NewField(&ast.Field{Name: ast.NewName(&ast.Name{Value: "__typename"})}))
return visitor.ActionUpdate, ast.NewSelectionSet(&ast.SelectionSet{Selections: selections})
},
},
},
}, nil)
// Visit returns nil when nothing changed (#165).
if edited == nil {
return doc
}
return edited.(*ast.Document)
}A rewrite can turn a valid document into an invalid one: removing fields can
leave an empty selection set, which does not parse, or a variable that is no
longer used, which validation rejects. Validate the result against the schema
before sending or executing it. Even adding a field can conflict: the helper
skips a selection set that already uses the __typename response key, but an
alias of that name inside a fragment still clashes with the field it adds
around the fragment.
Visit applies the updates to the tree it is given as well, not only to the one
it returns (#161). Rewrite a
document that nothing else holds, such as one parsed for the purpose, and not a
document shared with a cache or other requests.
Type information
To know the schema types at each point of a document, wrap the visitor with a
TypeInfo from the graphql package. During the walk it tracks the parent type
(ParentType), the field’s definition (FieldDef), its type (Type), and the
input type, argument and directive being visited (InputType, Argument,
Directive):
// fieldTypes lists every field a document selects, with the type that
// declares it and the type it returns.
func fieldTypes(schema *graphql.Schema, doc *ast.Document) []string {
var out []string
info := graphql.NewTypeInfo(&graphql.TypeInfoConfig{Schema: schema})
visitor.Visit(doc, visitor.VisitWithTypeInfo(info, &visitor.VisitorOptions{
KindFuncMap: map[string]visitor.NamedVisitFuncs{
kinds.Field: {
Kind: func(p visitor.VisitFuncParams) (string, interface{}) {
field := p.Node.(*ast.Field)
if def := info.FieldDef(); def != nil {
out = append(out, fmt.Sprintf("%s.%s: %s", info.ParentType(), field.Name.Value, def.Type))
}
return visitor.ActionNoChange, nil
},
},
},
}), nil)
return out
}A field that the schema does not have has no definition, so FieldDef returns
nil; validation reports it.
Complete program
main.go
package main
import (
"fmt"
"log"
"github.com/gql-go/graphql"
"github.com/gql-go/graphql/language/ast"
"github.com/gql-go/graphql/language/kinds"
"github.com/gql-go/graphql/language/parser"
"github.com/gql-go/graphql/language/printer"
"github.com/gql-go/graphql/language/source"
"github.com/gql-go/graphql/language/visitor"
)
// parse parses a document, naming it after the file it came from so that
// syntax errors say where they are.
func parse(name, body string) (*ast.Document, error) {
return parser.Parse(parser.ParseParams{
Source: source.NewSource(&source.Source{Body: []byte(body), Name: name}),
})
}
// fieldTypes lists every field a document selects, with the type that
// declares it and the type it returns.
func fieldTypes(schema *graphql.Schema, doc *ast.Document) []string {
var out []string
info := graphql.NewTypeInfo(&graphql.TypeInfoConfig{Schema: schema})
visitor.Visit(doc, visitor.VisitWithTypeInfo(info, &visitor.VisitorOptions{
KindFuncMap: map[string]visitor.NamedVisitFuncs{
kinds.Field: {
Kind: func(p visitor.VisitFuncParams) (string, interface{}) {
field := p.Node.(*ast.Field)
if def := info.FieldDef(); def != nil {
out = append(out, fmt.Sprintf("%s.%s: %s", info.ParentType(), field.Name.Value, def.Type))
}
return visitor.ActionNoChange, nil
},
},
},
}), nil)
return out
}
// withTypename adds __typename to every selection set that does not
// already use that response key, so that clients can tell the type of each
// object, as client caches do. Visit edits doc in place (#161), so pass a
// document that nothing else uses.
func withTypename(doc *ast.Document) *ast.Document {
edited := visitor.Visit(doc, &visitor.VisitorOptions{
KindFuncMap: map[string]visitor.NamedVisitFuncs{
kinds.SelectionSet: {
Leave: func(p visitor.VisitFuncParams) (string, interface{}) {
set := p.Node.(*ast.SelectionSet)
for _, sel := range set.Selections {
f, ok := sel.(*ast.Field)
if !ok {
continue
}
// Skip sets that already use the response key,
// even as an alias of another field.
key := f.Name.Value
if f.Alias != nil {
key = f.Alias.Value
}
if key == "__typename" {
return visitor.ActionNoChange, nil
}
}
selections := append(append([]ast.Selection{}, set.Selections...),
ast.NewField(&ast.Field{Name: ast.NewName(&ast.Name{Value: "__typename"})}))
return visitor.ActionUpdate, ast.NewSelectionSet(&ast.SelectionSet{Selections: selections})
},
},
},
}, nil)
// Visit returns nil when nothing changed (#165).
if edited == nil {
return doc
}
return edited.(*ast.Document)
}
func main() {
authorType := graphql.NewObject(graphql.ObjectConfig{
Name: "Author",
Fields: graphql.Fields{
"name": &graphql.Field{Type: graphql.String},
},
})
bookType := graphql.NewObject(graphql.ObjectConfig{
Name: "Book",
Fields: graphql.Fields{
"title": &graphql.Field{Type: graphql.NewNonNull(graphql.String)},
"author": &graphql.Field{Type: authorType},
},
})
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"books": &graphql.Field{Type: graphql.NewList(bookType)},
},
}),
})
if err != nil {
log.Fatal(err)
}
doc, err := parse("books.graphql", `
query Books { books { ...BookFields } }
fragment BookFields on Book { title author { name } }`)
if err != nil {
log.Fatal(err)
}
for _, line := range fieldTypes(&schema, doc) {
fmt.Println(line)
}
fmt.Println()
fmt.Print(printer.Print(withTypename(doc)))
fmt.Println()
_, err = parse("broken.graphql", `{ books { title }`)
fmt.Println(err)
}The program lists the fields of a document with their types, prints the
document with __typename added, and shows a syntax error from a named source:
Query.books: [Book]
Book.title: String!
Book.author: Author
Author.name: String
query Books {
books {
...BookFields
__typename
}
__typename
}
fragment BookFields on Book {
title
author {
name
__typename
}
__typename
}
Syntax Error broken.graphql (1:18) Expected Name, found EOF
1: { books { title }
^