Do and Execute
graphql.Do takes a request as text and returns a *graphql.Result.
graphql.Execute takes a document that is already parsed, which lets you parse
and validate it once and run it many times. This page covers both; the
complete program is at the end.
Do
result := graphql.Do(graphql.Params{
Schema: schema,
RequestString: document,
OperationName: "BookTitle",
VariableValues: map[string]interface{}{"id": "1"},
})| Field | Content |
|---|---|
Schema | The schema to run against. |
RequestString | The GraphQL document, as sent by the client. |
OperationName | Which operation to run, when the document has more than one. |
VariableValues | The values of the operation’s variables, usually decoded from JSON. |
RootObject | The Source of the root fields; see Root value. |
Context | The request’s context; see Context. |
Do parses the document, validates it with the
specified rules,
and executes the operation. A failure in parsing, in validation or in the
variables stops the request before any resolver runs: data is null and
errors explains why. A failure inside a resolver makes its field null, and
the rest of data is returned with it; when the field is non-null, the null
moves up to the nearest nullable parent, which is data itself for a root
field.
Operations
A document can hold several named operations. OperationName selects one; it
can be left out only when there is a single operation:
Must provide operation name if query contains multiple operations.
Unknown operation named "C".Variables
VariableValues holds the variables as Go values, usually the variables object
of an HTTP request decoded with encoding/json. They are coerced to the types
the operation declares before execution, and a missing required variable stops
the request:
Variable "$n" of required type "String!" was not provided.Coercion is more lenient than the specification in some cases: for example, the
number 3 given for a String! variable reaches the resolver as "3" instead
of being rejected (#10).
Root value
The Source of the root fields is RootObject. Use it for values that every
root resolver may need:
graphql.Do(graphql.Params{
Schema: schema,
RequestString: `{ library }`,
RootObject: map[string]interface{}{"library": "Roke"},
})Without RootObject, root resolvers receive a nil map[string]interface{}
from Do: reading from it works, but assigning a key panics. Pass an
initialized map when resolvers write to it. (Execute without Root passes an
empty map.)
For values that depend on the request, such as the signed-in user, the
context is usually a better place.
The result
| Field | Content |
|---|---|
Data | The response data, a map[string]interface{}, or nil. |
Errors | The errors, as gqlerrors.FormattedError values with message, locations and path. Omitted from the JSON when empty. |
Extensions | Values added by extensions. Omitted from the JSON when empty. |
result.HasErrors() tells whether there are errors, and result.ErrorsJoined()
(v0.12.0) combines them into one Go error that works with errors.Is and
errors.As, down to the errors your resolvers returned. The result encodes to
the JSON shape of the specification with encoding/json, so an HTTP handler can
write it as it is.
Execute
graphql.Execute runs a parsed document. It is the way to parse and validate a
document once, for example a document that clients send again and again, and to
run it with different variables:
// prepare parses and validates a document once, so that it can be executed
// many times.
func prepare(schema graphql.Schema, query string) (*ast.Document, error) {
doc, err := parser.Parse(parser.ParseParams{Source: query})
if err != nil {
return nil, err
}
if result := graphql.ValidateDocument(&schema, doc, nil); !result.IsValid {
return nil, fmt.Errorf("invalid document: %v", result.Errors)
}
return doc, nil
}doc, err := prepare(schema, `query ($id: ID!) { book(id: $id) { id title } }`)
if err != nil {
log.Fatal(err)
}
result := graphql.Execute(graphql.ExecuteParams{
Schema: schema,
AST: doc,
Args: map[string]interface{}{"id": "2"},
})ExecuteParams names some fields differently from Params: Args holds the
variables and Root the root value.
Execute does not validate. Validate the document before executing it, as
prepare does. An invalid document is executed as far as possible, with
results that depend on the error: a field that does not exist is left out of
data without an error, as is a fragment on a type the schema does not have
(v0.14.0), and a required argument that is missing reaches the
resolver as nil, so p.Args["id"].(string) panics and the field fails with
interface conversion: interface {} is nil, not string.
ValidateDocument(&schema, doc, nil) uses the specified rules. A non-empty list
replaces them rather than adding to them: to add a check, pass
append(graphql.SpecifiedRules, myRule).
Complete program
main.go
package main
import (
"encoding/json"
"fmt"
"log"
"github.com/gql-go/graphql"
"github.com/gql-go/graphql/language/ast"
"github.com/gql-go/graphql/language/parser"
)
type Book struct {
ID string `json:"id"`
Title string `json:"title"`
}
var books = map[string]*Book{
"1": {ID: "1", Title: "A Wizard of Earthsea"},
"2": {ID: "2", Title: "The Tombs of Atuan"},
}
func newSchema() (graphql.Schema, error) {
bookType := graphql.NewObject(graphql.ObjectConfig{
Name: "Book",
Fields: graphql.Fields{
"id": &graphql.Field{Type: graphql.NewNonNull(graphql.ID)},
"title": &graphql.Field{Type: graphql.NewNonNull(graphql.String)},
},
})
queryType := graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"book": &graphql.Field{
Type: bookType,
Args: graphql.FieldConfigArgument{
"id": &graphql.ArgumentConfig{Type: graphql.NewNonNull(graphql.ID)},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return books[p.Args["id"].(string)], nil
},
},
"library": &graphql.Field{
Type: graphql.String,
// The root Source is the RootObject given to Do or Execute.
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return p.Source.(map[string]interface{})["library"], nil
},
},
},
})
return graphql.NewSchema(graphql.SchemaConfig{Query: queryType})
}
// prepare parses and validates a document once, so that it can be executed
// many times.
func prepare(schema graphql.Schema, query string) (*ast.Document, error) {
doc, err := parser.Parse(parser.ParseParams{Source: query})
if err != nil {
return nil, err
}
if result := graphql.ValidateDocument(&schema, doc, nil); !result.IsValid {
return nil, fmt.Errorf("invalid document: %v", result.Errors)
}
return doc, nil
}
func printResult(result *graphql.Result) {
out, _ := json.Marshal(result)
fmt.Println(string(out))
}
func main() {
schema, err := newSchema()
if err != nil {
log.Fatal(err)
}
// Do: parse, validate and execute in one call.
document := `
query BookTitle($id: ID!) { book(id: $id) { title } }
query Library { library }`
printResult(graphql.Do(graphql.Params{
Schema: schema,
RequestString: document,
OperationName: "BookTitle",
VariableValues: map[string]interface{}{"id": "1"},
}))
printResult(graphql.Do(graphql.Params{
Schema: schema,
RequestString: document,
OperationName: "Library",
RootObject: map[string]interface{}{"library": "Roke"},
}))
// Execute: a document parsed and validated once, run with new variables.
doc, err := prepare(schema, `query ($id: ID!) { book(id: $id) { id title } }`)
if err != nil {
log.Fatal(err)
}
for _, id := range []string{"1", "2", "3"} {
printResult(graphql.Execute(graphql.ExecuteParams{
Schema: schema,
AST: doc,
Args: map[string]interface{}{"id": id},
}))
}
// An invalid document is rejected by prepare, before any execution.
if _, err := prepare(schema, `{ book(id: "1") { isbn } }`); err != nil {
fmt.Println(err)
}
}Running it prints the two operations run with Do, the prepared document run
three times with Execute (there is no book 3), and the error for an invalid
document:
{"data":{"book":{"title":"A Wizard of Earthsea"}}}
{"data":{"library":"Roke"}}
{"data":{"book":{"id":"1","title":"A Wizard of Earthsea"}}}
{"data":{"book":{"id":"2","title":"The Tombs of Atuan"}}}
{"data":{"book":null}}
invalid document: [Cannot query field "isbn" on type "Book".]