Enums
An enum is a type with a fixed set of named values. In the schema and in queries
the values are names, such as HARDCOVER; in Go each name maps to a value of
your choice, usually a constant of a named type. This page adds a book format
to the catalogue; the complete program is at the end.
Defining an enum
graphql.NewEnum maps each name to its Go value:
type Format int
const (
Hardcover Format = iota + 1
Paperback
Ebook
Audiobook
)
formatType := graphql.NewEnum(graphql.EnumConfig{
Name: "Format",
Description: "How a book is published.",
Values: graphql.EnumValueConfigMap{
"HARDCOVER": &graphql.EnumValueConfig{Value: Hardcover},
"PAPERBACK": &graphql.EnumValueConfig{Value: Paperback},
"EBOOK": &graphql.EnumValueConfig{Value: Ebook},
"AUDIOBOOK": &graphql.EnumValueConfig{
Value: Audiobook,
DeprecationReason: "Audiobooks are no longer sold.",
},
},
})Value names follow the same rule as type names, [_a-zA-Z][_a-zA-Z0-9]*, and are
written in upper case by convention. An enum needs at least one value;
NewSchema reports Format values must be an object with value names as keys.
otherwise.
A Value must be comparable and not a pointer: use constants, strings or
numbers. The executor looks values up in a map, so a slice or map value fails
with runtime error: hash of unhashable type []int, and it dereferences the
resolver’s result first, so a pointer Value never matches.
graphql.TypedEnum (v0.14.0) builds the same enum from values that all have
one Go type, so that a value of another type, such as the plain string
"hardcover" where a Format is expected, does not compile:
formatType := graphql.TypedEnum(graphql.TypedEnumConfig[Format]{
Name: "Format",
Description: "How a book is published.",
Values: map[string]graphql.TypedEnumValue[Format]{
"HARDCOVER": {Value: Hardcover},
"PAPERBACK": {Value: Paperback},
"EBOOK": {Value: Ebook},
"AUDIOBOOK": {Value: Audiobook, DeprecationReason: "Audiobooks are no longer sold."},
},
})It returns a *graphql.Enum, used like the one above. The type parameter must
be comparable, so a slice or map type does not compile. An interface type such
as any is comparable, though, and the values held in it are not checked: a
slice inside one still fails when the enum is used. A Value left out is the zero value of the type, such as 0
or "", not the name. A typed field
checks its arguments struct against the Go type of the values, and the strict
and report serialization modes convert a resolver result of another type with
the same kind, as described in Enum fields.
In NewEnum, when Value is omitted, the value is the name itself, as a
string:
sortOrderType := graphql.NewEnum(graphql.EnumConfig{
Name: "SortOrder",
Values: graphql.EnumValueConfigMap{
"ASC": &graphql.EnumValueConfig{},
"DESC": &graphql.EnumValueConfig{},
},
})Enum fields
A field of an enum type returns the Go value, and the executor writes its name
in the response. Book.format returns the Format field of the struct, and the
response contains "HARDCOVER". A pointer to a value works too.
The lookup compares Go values exactly, including their type. With
Value: Hardcover, a resolver that returns Format(1) or &book.Format
matches, but one that returns the plain int 1 or an int64 does not: these
are different values in Go. In a nullable field, a value that matches no enum
value becomes null without an error; in a non-null field such as
Book.format, the null is reported as
Cannot return null for non-nullable field Book.format. and moves up to the
parent. Return the same type you used in Value.
With strict serialization
(v0.11.0), a value that matches no enum value is a field error instead:
Enum "Format" cannot represent value: 9Report mode lists these values without changing responses, which helps find them before switching to strict mode.
A value of another Go type with the same kind, such as the plain int 1 for
Format(1) or a string for a value of a named string type, is converted in
the report and strict modes (v0.14.0) when it then equals exactly one enum
value: strict mode returns the name, and both report the value as
corrected. The lenient mode still returns null for it. When it equals
more than one, such as a string "x" for both Status("x") and
Kind("x"), or for two names that share a value, it stays invalid and the
error names the candidates:
Enum "Mixed" cannot represent value: "x" (ambiguous: A, B)Only the kind is compared, not the size: an int64 is not converted for an
int value. A wrapper such as sql.NullString is unwrapped first, through its
driver.Valuer method.
Enum arguments
An enum argument arrives in p.Args as the Go value, not as the name:
format: HARDCOVER arrives as Hardcover, of type Format, and order: DESC
as the string "DESC".
"books": &graphql.Field{
Type: graphql.NewNonNull(graphql.NewList(graphql.NewNonNull(bookType))),
Args: graphql.FieldConfigArgument{
"format": &graphql.ArgumentConfig{Type: formatType},
"order": &graphql.ArgumentConfig{Type: sortOrderType, DefaultValue: "ASC"},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
format, filtered := p.Args["format"].(Format)
// ...
},
},A DefaultValue is passed to the resolver as it is, so give it the Go value:
Hardcover for Format, "ASC" for SortOrder.
In a query, an enum value is written as a bare name. A quoted string or an unknown name fails validation:
Argument "format" has invalid value "HARDCOVER".
Expected type "Format", found "HARDCOVER".In variables, which arrive as JSON, the value is the name as a string:
graphql.Do(graphql.Params{
Schema: schema,
RequestString: `query ($order: SortOrder) { books(order: $order) { title } }`,
VariableValues: map[string]interface{}{"order": "DESC"},
})Deprecated values
A value with a DeprecationReason keeps working in queries and responses.
Introspection hides it unless the client asks with includeDeprecated: true,
and then reports isDeprecated and the reason, so tools such as GraphiQL show
it as deprecated.
Order of values
Values is a Go map, so the library does not know the order in which the
values were written. Introspection currently lists them in an order that can
change between runs of the program
(#98). Do not depend on that
order, for example in snapshot tests of an introspection result.
Complete program
main.go
package main
import (
"encoding/json"
"fmt"
"log"
"sort"
"github.com/gql-go/graphql"
)
// Format is how a book is published.
type Format int
const (
Hardcover Format = iota + 1
Paperback
Ebook
Audiobook
)
type Book struct {
Title string `json:"title"`
Format Format `json:"format"`
}
var books = []*Book{
{Title: "The Dispossessed", Format: Paperback},
{Title: "A Wizard of Earthsea", Format: Hardcover},
{Title: "The Left Hand of Darkness", Format: Ebook},
}
func newSchema() (graphql.Schema, error) {
formatType := graphql.NewEnum(graphql.EnumConfig{
Name: "Format",
Description: "How a book is published.",
Values: graphql.EnumValueConfigMap{
"HARDCOVER": &graphql.EnumValueConfig{Value: Hardcover},
"PAPERBACK": &graphql.EnumValueConfig{Value: Paperback},
"EBOOK": &graphql.EnumValueConfig{Value: Ebook},
"AUDIOBOOK": &graphql.EnumValueConfig{
Value: Audiobook,
DeprecationReason: "Audiobooks are no longer sold.",
},
},
})
// Without Value, each enum value is represented by its name.
sortOrderType := graphql.NewEnum(graphql.EnumConfig{
Name: "SortOrder",
Values: graphql.EnumValueConfigMap{
"ASC": &graphql.EnumValueConfig{},
"DESC": &graphql.EnumValueConfig{},
},
})
bookType := graphql.NewObject(graphql.ObjectConfig{
Name: "Book",
Fields: graphql.Fields{
"title": &graphql.Field{Type: graphql.NewNonNull(graphql.String)},
"format": &graphql.Field{Type: graphql.NewNonNull(formatType)},
},
})
queryType := graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"books": &graphql.Field{
Type: graphql.NewNonNull(graphql.NewList(graphql.NewNonNull(bookType))),
Args: graphql.FieldConfigArgument{
"format": &graphql.ArgumentConfig{Type: formatType},
"order": &graphql.ArgumentConfig{Type: sortOrderType, DefaultValue: "ASC"},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
var result []*Book
for _, b := range books {
if format, ok := p.Args["format"].(Format); ok && b.Format != format {
continue
}
result = append(result, b)
}
desc := p.Args["order"] == "DESC"
sort.Slice(result, func(i, j int) bool {
if desc {
return result[i].Title > result[j].Title
}
return result[i].Title < result[j].Title
})
return result, nil
},
},
},
})
return graphql.NewSchema(graphql.SchemaConfig{Query: queryType})
}
func main() {
schema, err := newSchema()
if err != nil {
log.Fatal(err)
}
query := `query ($order: SortOrder) {
all: books(order: $order) { title format }
hardcovers: books(format: HARDCOVER) { title }
}`
result := graphql.Do(graphql.Params{
Schema: schema,
RequestString: query,
VariableValues: map[string]interface{}{"order": "DESC"},
})
out, _ := json.MarshalIndent(result, "", " ")
fmt.Println(string(out))
}all and hardcovers are aliases: the same field asked for twice with different
arguments. Running the program prints:
{
"data": {
"all": [
{
"format": "EBOOK",
"title": "The Left Hand of Darkness"
},
{
"format": "PAPERBACK",
"title": "The Dispossessed"
},
{
"format": "HARDCOVER",
"title": "A Wizard of Earthsea"
}
],
"hardcovers": [
{
"title": "A Wizard of Earthsea"
}
]
}
}