Objects and fields
An object type is a named set of fields, and most of a schema is made of them. Each field has a type, optional arguments, and a resolver that produces its value. This page builds a small catalogue of books and authors that uses each of these pieces; the complete program is at the end.
Defining an object
graphql.NewObject creates an object type from an ObjectConfig:
bookType := graphql.NewObject(graphql.ObjectConfig{
Name: "Book",
Description: "A book in the catalogue.",
Fields: graphql.Fields{
"id": &graphql.Field{Type: graphql.NewNonNull(graphql.ID)},
"title": &graphql.Field{Type: graphql.NewNonNull(graphql.String)},
"tags": &graphql.Field{Type: graphql.NewList(graphql.NewNonNull(graphql.String))},
},
})The name must match [_a-zA-Z][_a-zA-Z0-9]* and be unique in the schema. The
description is shown by introspection, and so by tools such as GraphiQL.
A graphql.Field has these options:
| Option | Purpose |
|---|---|
Type | The type of the value: a scalar, object, interface, union or enum, possibly wrapped in a list or non-null. |
Args | The arguments the field accepts. See Arguments. |
Resolve | The function that returns the value. Optional. |
Description | Documentation shown by introspection. |
DeprecationReason | Marks the field as deprecated, with the reason shown by introspection. The field keeps working. |
Resolving a field
A resolver receives a graphql.ResolveParams and returns the value of the field
and an error:
"author": &graphql.Field{
Type: graphql.NewNonNull(authorType),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
book := p.Source.(*Book)
return authors[book.AuthorID], nil
},
},p.Source is the value returned for the parent object; here, the *Book that
the book or books field returned. On the root type it is the RootObject
given to graphql.Do, or an empty map[string]interface{} when none is given.
A field without Resolve uses the default resolver, which reads the field from
the source: a map key with the field’s name, or the first struct field whose name
matches it ignoring case, or whose json or graphql tag matches it exactly. In
the example, id, title and tags come from the Book struct this way.
A resolver that returns an error, or panics, produces a field error: the field
is null, the error is listed in the response’s errors with its path, and the
other fields resolve normally.
Arguments
Args declares the arguments of a field, and the resolver reads them from
p.Args:
"books": &graphql.Field{
Type: graphql.NewNonNull(graphql.NewList(graphql.NewNonNull(bookType))),
Args: graphql.FieldConfigArgument{
"limit": &graphql.ArgumentConfig{
Type: graphql.Int,
DefaultValue: 10,
Description: "Maximum number of books to return.",
},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
limit := p.Args["limit"].(int)
if limit < 0 {
return nil, fmt.Errorf("limit must not be negative, got %d", limit)
}
if limit < len(books) {
return books[:limit], nil
}
return books, nil
},
},Arguments are validated and coerced before the resolver runs, so a resolver can rely on their types. A query that omits a non-null argument, or passes a value of the wrong type, fails validation and no resolver runs:
{
"data": null,
"errors": [
{
"message": "Field \"book\" argument \"id\" of type \"ID!\" is required but not provided.",
"locations": [{ "line": 1, "column": 3 }]
}
]
}The values in p.Args have these Go types:
| GraphQL type | Go type in p.Args |
|---|---|
Int | int |
Float | float64 |
String, ID | string (an ID given as 7 arrives as "7") |
Boolean | bool |
| Enum | the enum value’s Value |
| List | []interface{}; a single value passed to a list argument arrives as a list of one |
| Input object | map[string]interface{} |
A DefaultValue is passed to the resolver as it is, without coercion, so give
it the Go type from this table: DefaultValue: 10 on a Float argument arrives
as int when the query omits the argument, and p.Args["rate"].(float64)
panics. Write 10.0 instead.
An argument that the query omits and that has no DefaultValue is absent from
p.Args; read it with the two-value form, v, ok := p.Args["limit"].
Null and omitted arguments
The specification treats books, books(limit: null) and books(limit: 5) as
three different requests: omitted, where the default applies; an explicit
null, which the resolver receives as null; and a value. By default, as in
the original library, an explicit null is treated like an omitted argument:
p.Args["limit"] is 10 in the first two requests. Inside an input object,
the default is not consistent: a field written as null in the query is
dropped even when it has a default, while a field sent as null in a variable
gets its default.
p.ArgumentState tells the three cases apart in every mode (v0.12.0). It
takes the argument name, followed by input field names and list indexes for a
value inside it:
switch p.ArgumentState("limit") {
case graphql.ArgumentOmitted: // not in the query, or a variable that was not sent
case graphql.ArgumentNull: // limit: null, or a variable sent as null
case graphql.ArgumentSet: // any other value
}This is what an update needs to tell “clear the description”, {description: null}, from “leave it as it is”, no description:
p.ArgumentState("input", "description").
The indexes are those of p.Args: a single value given for a list argument,
such as tags: "x", is at index 0 (since v0.14.0; before, it read as
omitted).
A struct decoded with graphql.ArgsAs (v0.14.0) carries the same answer
in fields of type graphql.Optional[T], which hold the state next to the value:
type UpdateBookArgs struct {
ID string `graphql:"id"`
Input struct {
Title graphql.Optional[string] `graphql:"title"`
Description graphql.Optional[string] `graphql:"description"`
} `graphql:"input"`
}
args, err := graphql.ArgsAs[UpdateBookArgs](p)
if err != nil {
return nil, err
}
if title, ok := args.Input.Title.Get(); ok {
book.Title = title
}
if args.Input.Description.State() == graphql.ArgumentNull {
book.Description = ""
}Get returns the value and whether the request gave one, State returns the
ArgumentState, and Value returns what p.Args holds, which is the
DefaultValue when the request gave none.
Inside the value of a custom scalar, the state does not come from the request,
which gives the scalar as one value: it comes from what the scalar’s
ParseValue or ParseLiteral returned. A key with a value is set, a key with
nil is null and a missing key is omitted, whether the client wrote that key
or the scalar added it. See
Typed arguments and sources.
The Coercion option of the schema (v0.12.0) makes p.Args itself follow
the specification:
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: queryType,
Coercion: graphql.CoercionConfig{
Mode: graphql.CoercionReport,
OnDifference: func(ctx context.Context, d graphql.CoercionDifference) {
log.Printf("%s %s.%s %v at %v", d.Kind, d.ParentType, d.FieldName, d.Argument, d.Path)
},
},
})CoercionSpeckeeps an explicitnullinp.Args, as the specification andgraphql-jsdo:p.Args["limit"]isnilforbooks(limit: null), even thoughlimithas aDefaultValue, and an input object keeps a field sent asnullas a key with anilvalue. ADefaultValueapplies only when the value is omitted.CoercionReportkeeps the defaultp.Argsand callsOnDifferencewherever spec mode would behave differently, with aKind:null dropped: the key is absent by default;null defaulted: the default replaces thenull, inLegacyValue;default applied: an input field whose variable is not sent gets its default in spec mode, inSpecValue, and is absent by default;null rejected: a variable with a default, such as$v: String = "a", is sent asnullfor a non-null argument or field. By default the default is used; spec mode returns a field error, such asArgument "id" of non-null type "ID!" must not be null., and the resolver does not run.
Spec mode changes p.Args for every resolver of the schema, and a resolver
written for the default can fail: in spec mode, books(limit: null) makes
p.Args["limit"].(int) panic, which the executor reports as a field error.
Any single-value type assertion on p.Args, such as p.Args["x"].(T), fails
this way when the client sends null, also for an argument with a
DefaultValue.
If your resolvers use that pattern widely, stay in the default mode and call
p.ArgumentState in the resolvers that need to tell null from omitted. To
switch to spec mode instead, run report mode first, fix the resolvers it points
to, and only then switch. Report mode can log a lot: every explicit null
sent where there is a DefaultValue is reported, as null defaulted, or as
null dropped for an input object field written as null in the query. In a
schema that gives most arguments a default, that can be nearly every request,
so filter by Kind or field, or sample, in OnDifference. A resolver that works in both modes reads the value
with the two-value form:
limit, ok := p.Args["limit"].(int)
if !ok {
limit = len(books) // limit: null returns every book
}Lists and non-null
Every type is nullable unless it is wrapped in graphql.NewNonNull, and
graphql.NewList makes a list of another type. The wrappers combine:
graphql.String // String
graphql.NewNonNull(graphql.String) // String!
graphql.NewList(graphql.String) // [String]
graphql.NewNonNull(graphql.NewList(graphql.NewNonNull(graphql.String))) // [String!]!| GraphQL | Meaning |
|---|---|
String | A string or null. |
String! | Never null. |
[String] | null, or a list whose items may be null. |
[String!]! | Always a list, and no item is null. |
A list field accepts any Go slice or array. A nil slice is returned as an
empty list; return nil itself for null.
Non-null is a promise that the executor enforces. When a non-null field resolves
to null, the field is reported as an error and the null moves up to the
nearest parent that can be null. If the catalogue had a book whose author is
missing, Book.author, an Author!, would resolve to null and the whole book
would become null:
{
"data": { "book": null },
"errors": [
{
"message": "Cannot return null for non-nullable field Book.author.",
"locations": [{ "line": 1, "column": 25 }],
"path": ["book", "author"]
}
]
}Make a field non-null when the value can always be produced, such as an ID, and leave it nullable when a failure to produce it should not hide its siblings.
Types that refer to each other
Author.books returns books and Book.author returns an author, so each type
refers to the other. Go evaluates the arguments of NewObject immediately, which
gives two ways to build such types.
FieldsThunk: pass the fields as a function, which the library calls once
both types exist:
var bookType *graphql.Object
authorType := graphql.NewObject(graphql.ObjectConfig{
Name: "Author",
Fields: graphql.FieldsThunk(func() graphql.Fields {
return graphql.Fields{
"name": &graphql.Field{Type: graphql.String},
"books": &graphql.Field{Type: graphql.NewList(bookType)},
}
}),
})
bookType = graphql.NewObject(graphql.ObjectConfig{
Name: "Book",
Fields: graphql.Fields{
"title": &graphql.Field{Type: graphql.String},
"author": &graphql.Field{Type: authorType},
},
})Build the types inside a function, as above. With package-level variables the Go
compiler rejects the thunk with initialization cycle for authorType, because
the function refers to bookType, whose initializer refers to authorType.
AddFieldConfig: with package-level variables, define one side without the
field that closes the cycle, and add it in init:
var authorType = graphql.NewObject(graphql.ObjectConfig{
Name: "Author",
Fields: graphql.Fields{
"name": &graphql.Field{Type: graphql.String},
},
})
var bookType = graphql.NewObject(graphql.ObjectConfig{
Name: "Book",
Fields: graphql.Fields{
"title": &graphql.Field{Type: graphql.String},
"author": &graphql.Field{Type: authorType},
},
})
func init() {
authorType.AddFieldConfig("books", &graphql.Field{
Type: graphql.NewList(bookType),
})
}AddFieldConfig works when Fields is a graphql.Fields map, and must run
before graphql.NewSchema.
The schema
Objects become reachable through the root types of a schema: Query is
required, and Mutation and Subscription are optional.
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: queryType,
})NewSchema checks every type reachable from the roots and returns the first
problem as an error, for example:
Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "Bad-Name" does not.
Empty fields must be an object with field names as keys or a function which return such an object.Build the schema once, at startup, and reuse it for every request.
Complete program
main.go
package main
import (
"encoding/json"
"fmt"
"log"
"github.com/gql-go/graphql"
)
type Author struct {
ID string `json:"id"`
Name string `json:"name"`
}
type Book struct {
ID string `json:"id"`
Title string `json:"title"`
Tags []string `json:"tags"`
AuthorID string `json:"-"`
}
var authors = map[string]*Author{
"1": {ID: "1", Name: "Ursula K. Le Guin"},
}
var books = []*Book{
{ID: "1", Title: "A Wizard of Earthsea", Tags: []string{"fantasy"}, AuthorID: "1"},
{ID: "2", Title: "The Dispossessed", Tags: []string{"science fiction"}, AuthorID: "1"},
}
func newSchema() (graphql.Schema, error) {
// Declared first so that the Author fields can refer to it.
var bookType *graphql.Object
authorType := graphql.NewObject(graphql.ObjectConfig{
Name: "Author",
Description: "A person who wrote at least one book.",
Fields: graphql.FieldsThunk(func() graphql.Fields {
return graphql.Fields{
"id": &graphql.Field{Type: graphql.NewNonNull(graphql.ID)},
"name": &graphql.Field{Type: graphql.NewNonNull(graphql.String)},
"books": &graphql.Field{
Type: graphql.NewNonNull(graphql.NewList(graphql.NewNonNull(bookType))),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
author := p.Source.(*Author)
var written []*Book
for _, b := range books {
if b.AuthorID == author.ID {
written = append(written, b)
}
}
return written, nil
},
},
}
}),
})
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)},
"tags": &graphql.Field{Type: graphql.NewList(graphql.NewNonNull(graphql.String))},
"author": &graphql.Field{
Type: graphql.NewNonNull(authorType),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return authors[p.Source.(*Book).AuthorID], nil
},
},
},
})
queryType := graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"book": &graphql.Field{
Type: bookType,
Description: "Looks up a book by its ID.",
Args: graphql.FieldConfigArgument{
"id": &graphql.ArgumentConfig{Type: graphql.NewNonNull(graphql.ID)},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
id := p.Args["id"].(string)
for _, b := range books {
if b.ID == id {
return b, nil
}
}
return nil, nil
},
},
"books": &graphql.Field{
Type: graphql.NewNonNull(graphql.NewList(graphql.NewNonNull(bookType))),
Args: graphql.FieldConfigArgument{
"limit": &graphql.ArgumentConfig{
Type: graphql.Int,
DefaultValue: 10,
Description: "Maximum number of books to return.",
},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
limit := p.Args["limit"].(int)
if limit < 0 {
return nil, fmt.Errorf("limit must not be negative, got %d", limit)
}
if limit < len(books) {
return books[:limit], nil
}
return books, nil
},
},
},
})
return graphql.NewSchema(graphql.SchemaConfig{Query: queryType})
}
func main() {
schema, err := newSchema()
if err != nil {
log.Fatal(err)
}
query := `{
book(id: "1") {
title
author {
name
books { title }
}
}
}`
result := graphql.Do(graphql.Params{Schema: schema, RequestString: query})
out, _ := json.MarshalIndent(result, "", " ")
fmt.Println(string(out))
}Running it prints:
{
"data": {
"book": {
"author": {
"books": [
{
"title": "A Wizard of Earthsea"
},
{
"title": "The Dispossessed"
}
],
"name": "Ursula K. Le Guin"
},
"title": "A Wizard of Earthsea"
}
}
}The keys come out in alphabetical order because result.Data is a map and
encoding/json sorts map keys.