Input objects
An input object groups several values into one argument, such as the data of a
new book passed to a mutation. Its fields can be scalars, enums, lists and other
input objects, but not object types. This page adds an addBook mutation to the
catalogue; the complete program is at the end.
Defining an input object
graphql.NewInputObject takes a map of fields. Each field has a type, and
optionally a default value and a description:
addBookInputType := graphql.NewInputObject(graphql.InputObjectConfig{
Name: "AddBookInput",
Description: "The data needed to add a book to the catalogue.",
Fields: graphql.InputObjectConfigFieldMap{
"title": &graphql.InputObjectFieldConfig{Type: graphql.NewNonNull(graphql.String)},
"pages": &graphql.InputObjectFieldConfig{Type: graphql.Int},
"format": &graphql.InputObjectFieldConfig{
Type: formatType,
DefaultValue: Paperback,
},
"tags": &graphql.InputObjectFieldConfig{Type: graphql.NewList(graphql.NewNonNull(graphql.String))},
},
})It is used as the type of an argument, usually non-null:
"addBook": &graphql.Field{
Type: graphql.NewNonNull(bookType),
Args: graphql.FieldConfigArgument{
"input": &graphql.ArgumentConfig{Type: graphql.NewNonNull(addBookInputType)},
},
Resolve: addBook,
},Input objects that refer to each other take their fields as a
graphql.InputObjectConfigFieldMapThunk, as objects do with FieldsThunk.
Use input types only where the specification allows them: scalars, enums and
input objects (and lists and non-null of those) for arguments and input fields,
and object types for the fields of objects. NewSchema does not check this yet
(#101), so a mistake shows up
only when a query reaches the field.
Reading the value
The argument arrives in p.Args as a map[string]interface{}, with each field
coerced like an argument of its type: Int as int, an enum as its Go value, a
list as []interface{}, and a nested input object as another
map[string]interface{}.
input := p.Args["input"].(map[string]interface{})
title := input["title"].(string)
pages, hasPages := input["pages"].(int)A field that the client omits is absent from the map, unless it has a
DefaultValue. As with arguments, the default is passed as it is, without
coercion: give it the Go value (Paperback, not "PAPERBACK"), and the right Go
type (10.0 for a Float field).
Give defaults to nullable fields. A non-null field is currently required even when it has a default, in literals and in variables (#59).
By default, an explicit null for a field is not kept either: a variable
holding {"format": null} gets the field’s default, and format: null or
format: $f inside a literal, with $f set to null, leaves the field out of
the map. The specification keeps both as null. p.ArgumentState("input", "format") tells an explicit null from an omitted field, and the Coercion
option keeps the null in the map (v0.12.0); see
Null and omitted arguments.
Reading many fields from the map is tedious. graphql.ArgsAs (v0.14.0)
decodes the arguments of a field into a struct, input objects included:
type AddBookInput struct {
Title string `json:"title"`
Pages int `json:"pages"`
Format Format `json:"format"`
Tags []string `json:"tags"`
}
type AddBookArgs struct {
Input AddBookInput `json:"input"`
}
args, err := graphql.ArgsAs[AddBookArgs](p)When the struct does not match the schema, the error names the value, such as
graphql: cannot decode argument "input.pages": string does not fit int. The
rules are in
Typed arguments and sources.
Literals and variables
A client can write the input in the document:
mutation {
addBook(input: {title: "A Wizard of Earthsea", pages: 183, format: HARDCOVER}) {
id title format
}
}or, as HTTP clients usually do, send it as a variable, which arrives as JSON and
is coerced the same way, apart from explicit null values (above) and
non-integer numbers for Int (below):
graphql.Do(graphql.Params{
Schema: schema,
RequestString: `mutation ($input: AddBookInput!) { addBook(input: $input) { id } }`,
VariableValues: map[string]interface{}{
"input": map[string]interface{}{"title": "The Dispossessed"},
},
})Validation checks the input before any resolver runs. A missing non-null field, a field the type does not have, or a value of the wrong type is reported with the field that caused it:
Argument "input" has invalid value {pages: 183}.
In field "title": Expected "String!", found null.
Argument "input" has invalid value {title: "T", isbn: "0-06-093"}.
In field "isbn": Unknown field.
Argument "input" has invalid value {title: "T", pages: "183"}.
In field "pages": Expected type "Int", found "183".
Variable "$input" got invalid value {"pages":183}.
In field "title": Expected "String!", found null.Variables are coerced more leniently than literals in some cases: a variable
pages: 3.5 arrives as int(3) instead of being rejected, while the literal
pages: 3.5 fails validation. Aligning variable coercion with the
specification is tracked in #10.
Mutations
The example uses an input object in a mutation, the usual place for one. A
mutation is a field of the Mutation root type, given to NewSchema next to
Query:
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: queryType,
Mutation: mutationType,
})Mutation resolvers are where side effects belong. When a document has several mutation fields, their resolvers are called one after another, in document order, as the specification requires. A resolver that returns a function, to run concurrently, breaks that order: the functions run after all the resolvers, in an order that can change between executions (#102). Return the value directly from a mutation resolver whose order matters.
Complete program
main.go
package main
import (
"encoding/json"
"fmt"
"log"
"github.com/gql-go/graphql"
)
type Format int
const (
Hardcover Format = iota + 1
Paperback
Ebook
)
type Book struct {
ID string `json:"id"`
Title string `json:"title"`
Pages int `json:"pages"`
Format Format `json:"format"`
Tags []string `json:"tags"`
}
// AddBookInput mirrors the AddBookInput type of the schema.
type AddBookInput struct {
Title string `json:"title"`
Pages int `json:"pages"`
Format Format `json:"format"`
Tags []string `json:"tags"`
}
// AddBookArgs mirrors the arguments of the addBook field.
type AddBookArgs struct {
Input AddBookInput `json:"input"`
}
var books []*Book
func newSchema() (graphql.Schema, error) {
formatType := graphql.NewEnum(graphql.EnumConfig{
Name: "Format",
Values: graphql.EnumValueConfigMap{
"HARDCOVER": &graphql.EnumValueConfig{Value: Hardcover},
"PAPERBACK": &graphql.EnumValueConfig{Value: Paperback},
"EBOOK": &graphql.EnumValueConfig{Value: Ebook},
},
})
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)},
"pages": &graphql.Field{Type: graphql.Int},
"format": &graphql.Field{Type: graphql.NewNonNull(formatType)},
"tags": &graphql.Field{Type: graphql.NewList(graphql.NewNonNull(graphql.String))},
},
})
addBookInputType := graphql.NewInputObject(graphql.InputObjectConfig{
Name: "AddBookInput",
Description: "The data needed to add a book to the catalogue.",
Fields: graphql.InputObjectConfigFieldMap{
"title": &graphql.InputObjectFieldConfig{Type: graphql.NewNonNull(graphql.String)},
"pages": &graphql.InputObjectFieldConfig{Type: graphql.Int},
"format": &graphql.InputObjectFieldConfig{
Type: formatType,
DefaultValue: Paperback,
},
"tags": &graphql.InputObjectFieldConfig{Type: graphql.NewList(graphql.NewNonNull(graphql.String))},
},
})
queryType := graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"books": &graphql.Field{
Type: graphql.NewNonNull(graphql.NewList(graphql.NewNonNull(bookType))),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return books, nil
},
},
},
})
mutationType := graphql.NewObject(graphql.ObjectConfig{
Name: "Mutation",
Fields: graphql.Fields{
"addBook": &graphql.Field{
Type: graphql.NewNonNull(bookType),
Args: graphql.FieldConfigArgument{
"input": &graphql.ArgumentConfig{Type: graphql.NewNonNull(addBookInputType)},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
args, err := graphql.ArgsAs[AddBookArgs](p)
if err != nil {
return nil, err
}
in := args.Input
book := &Book{
ID: fmt.Sprint(len(books) + 1),
Title: in.Title,
Pages: in.Pages,
Format: in.Format,
Tags: in.Tags,
}
books = append(books, book)
return book, nil
},
},
},
})
return graphql.NewSchema(graphql.SchemaConfig{
Query: queryType,
Mutation: mutationType,
})
}
func main() {
schema, err := newSchema()
if err != nil {
log.Fatal(err)
}
// The input as a literal in the document.
literal := `mutation {
addBook(input: {title: "A Wizard of Earthsea", pages: 183, format: HARDCOVER}) {
id title format
}
}`
// The input as a variable, as an HTTP client sends it.
withVariable := `mutation ($input: AddBookInput!) {
addBook(input: $input) { id title format tags }
}`
variables := map[string]interface{}{
"input": map[string]interface{}{
"title": "The Dispossessed",
"tags": []interface{}{"science fiction", "utopia"},
},
}
for _, r := range []*graphql.Result{
graphql.Do(graphql.Params{Schema: schema, RequestString: literal}),
graphql.Do(graphql.Params{Schema: schema, RequestString: withVariable, VariableValues: variables}),
} {
out, _ := json.MarshalIndent(r, "", " ")
fmt.Println(string(out))
}
}The first mutation passes the input as a literal; the second as a variable,
without format, so the default PAPERBACK applies. Running the program
prints:
{
"data": {
"addBook": {
"format": "HARDCOVER",
"id": "1",
"title": "A Wizard of Earthsea"
}
}
}
{
"data": {
"addBook": {
"format": "PAPERBACK",
"id": "2",
"tags": [
"science fiction",
"utopia"
],
"title": "The Dispossessed"
}
}
}