Default resolver
A field without Resolve uses graphql.DefaultResolveFn, which reads the
field’s value from the parent value, p.Source. Most fields of a schema built
on Go structs or maps need no resolver at all. This page shows where the
default resolver looks and the cases where it does not find what you expect;
the complete program is at the end.
Where it looks
It tries the source in this order and stops at the first that applies:
- A
graphql.FieldResolver: if the source has a methodResolve(p graphql.ResolveParams) (interface{}, error), that method resolves every field of it. - A struct, or a pointer to one: the first field, in declaration order, that matches the GraphQL field (see Structs).
- A
map[string]interface{}: the value under the field’s name. - Any other map with
stringkeys, through reflection, such asmap[string]string.
When nothing matches, the value is nil: a nullable field is null without an
error, and a non-null field reports Cannot return null for non-nullable field
and the null propagates to its parent. The name used is
always the field’s name in the schema, also when the query gives it an alias.
A default resolver that reports a missing field as an error is on the roadmap
(#9).
Structs
A struct field matches when its name equals the GraphQL field’s name ignoring
case, or when its json or graphql tag gives exactly that name (the part
before the first comma, so json:"publisher,omitempty" gives publisher):
type Book struct {
ID string `json:"id"` // matched by its json tag
Title string // matched by its name, ignoring case
PageCount int `graphql:"pages"` // matched by its graphql tag
Subtitle *string `json:"subtitle"`
Edition sql.NullString `json:"edition"`
}Struct fields are checked in declaration order, and the first match wins. A few consequences:
- A tag adds a name; it does not remove one.
Hidden string `json:"-"`still matches a GraphQL field namedhidden, by its Go name. - Order decides between two matches. With
Title string `json:"name"`declared beforeName string, the GraphQL fieldnamereturnsTitle. - Methods are not called. A
Summary()method does not resolve asummaryfield; write a resolver, or implementFieldResolver. - Fields promoted from an embedded struct are not found by default. With
Baseembedded inBookandIDdeclared inBase,idisnull; see Embedded structs for the option that finds them. - An unexported field that matches is an error,
reflect.Value.Interface: cannot return value obtained from unexported field or method, even when an exported field further down would match by tag (#133). Rename the field or write a resolver.
A source that is a pointer to a struct is dereferenced. A pointer value is
dereferenced when the built-in scalar expects that Go type: *string for
String and ID, *int for Int, *float64 for Float and Int, *bool
for Boolean. So Subtitle *string gives the string, or null for a nil
pointer. Other combinations are not converted: in the default lenient mode a
String field given an *int returns the pointer’s address, such as
"0x154fe0a3e580".
Embedded structs
Models often embed a common struct, such as one with an ID and timestamps.
The DefaultResolver option of the schema (v0.15.0) makes the default
resolver find the fields such a struct promotes:
type Base struct {
ID string `json:"id"`
CreatedAt time.Time
}
type Book struct {
Base
Title string `json:"title"`
}
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: queryType,
DefaultResolver: graphql.DefaultResolverConfig{EmbeddedFields: true},
})With it, id and createdAt of a Book come from Base. The direct fields
of the source are still checked first, as described in Structs,
so nothing that resolves without the option changes. When no direct field
matches, the embedded structs are searched as Go promotes their fields:
- The shallowest match wins: a field of
Book.Basehides one with the same name in a struct thatBaseembeds. - Two matches at the same depth, such as
IDin two embedded structs, are ambiguous, and the field isnull. - An embedded struct whose
jsonorgraphqltag gives a name, such asBase `json:"base"`, is a field with that name, as inencoding/json, and its fields are not promoted; one tagged-is skipped. A tag with options only, such asjson:",omitempty", gives no name, and the fields are promoted. - An embedded pointer that is nil gives
nullfor its fields. - Exported fields of an unexported embedded struct are promoted, as in Go.
A field with the tag
json:"-"orgraphql:"-"is not. - A promoted field holds a value like a direct one: a field of type
func() (interface{}, error)is called, as for a concurrent resolver.
The path to each field is cached per Go type and field name. The
option applies to graphql.DefaultResolveFn during execution; called outside
execution, on a ResolveParams without a schema, it looks at direct fields
only.
Replacing the default resolver
The same option can replace the default resolver for every field without
Resolve (v0.15.0), for example to read values from a model that keeps them
behind a method:
DefaultResolver: graphql.DefaultResolverConfig{
EmbeddedFields: true,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
if record, ok := p.Source.(*Record); ok {
return record.Get(p.Info.FieldName), nil
}
return graphql.DefaultResolveFn(p)
},
},It runs for every such field of the schema, concurrently, so it should be
cheap and safe for concurrent use. Calling graphql.DefaultResolveFn for the
cases it does not handle keeps the behaviour described on this page,
EmbeddedFields included. A field with its own Resolve does not use it,
and neither do the fields of the built-in introspection types, such as
__Type, which keep the default resolver.
Wrapper types
Types such as sql.NullString, and null.* types built on them, are structs.
The default resolver returns the struct, and what the response shows depends on
the schema’s serialization mode:
| Mode | A valid sql.NullString{String: "first", Valid: true} |
|---|---|
| Lenient (default) | "{first true}", the struct printed by fmt |
Strict or report (v0.11.0) | strict returns "first"; report returns the lenient value and reports the difference |
Strict serialization unwraps any driver.Valuer, and for String and ID any
encoding.TextMarshaler or fmt.Stringer; an invalid wrapper becomes null.
See Custom scalars for
serializers of your own, which receive the wrapper as it is.
Maps
With a map[string]interface{} source, the value under the field’s name is
used. A value that is a function is treated specially:
| Value | Result |
|---|---|
func() interface{} | called, and its result is the value |
func() (interface{}, error) | run as a concurrent resolver |
| any other function | a field error: Error resolving func. Expected `func() (interface{}, error)` signature |
Maps with other value types, such as map[string]string, are read through
reflection. A map whose key is a named string type, such as
map[Key]string, fails today
(#58).
FieldResolver
A source type can resolve its own fields by implementing
graphql.FieldResolver, which is useful for computed values:
type Shelf struct {
Books []*Book
}
func (s Shelf) Resolve(p graphql.ResolveParams) (interface{}, error) {
switch p.Info.FieldName {
case "count":
return len(s.Books), nil
case "totalPages":
total := 0
for _, b := range s.Books {
total += b.PageCount
}
return total, nil
}
return nil, fmt.Errorf("unknown shelf field %q", p.Info.FieldName)
}The method is used for every field of the type that has no Resolve of its
own, so it should handle each of them.
Calling it from a resolver
graphql.DefaultResolveFn is exported, so a resolver can do some work and then
fall back to it:
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
if !allowed(p.Context) {
return nil, errors.New("not allowed")
}
return graphql.DefaultResolveFn(p)
},Complete program
main.go
package main
import (
"database/sql"
"encoding/json"
"fmt"
"log"
"strings"
"github.com/gql-go/graphql"
)
type Book struct {
ID string `json:"id"` // matched by its json tag
Title string // matched by its name, ignoring case
PageCount int `graphql:"pages"` // matched by its graphql tag
Subtitle *string `json:"subtitle"`
Edition sql.NullString `json:"edition"`
}
// Shelf computes its fields: the default resolver calls Resolve for every
// field of a source that implements graphql.FieldResolver.
type Shelf struct {
Books []*Book
}
func (s Shelf) Resolve(p graphql.ResolveParams) (interface{}, error) {
switch p.Info.FieldName {
case "count":
return len(s.Books), nil
case "totalPages":
total := 0
for _, b := range s.Books {
total += b.PageCount
}
return total, nil
}
return nil, fmt.Errorf("unknown shelf field %q", p.Info.FieldName)
}
func ptr(s string) *string { return &s }
var books = []*Book{
{ID: "1", Title: "A Wizard of Earthsea", PageCount: 183, Edition: sql.NullString{String: "first", Valid: true}},
{ID: "2", Title: "The Tombs of Atuan", PageCount: 163, Subtitle: ptr("Earthsea, book two")},
}
func newSchema() (graphql.Schema, error) {
authorType := graphql.NewObject(graphql.ObjectConfig{
Name: "Author",
Fields: graphql.Fields{
"name": &graphql.Field{Type: graphql.String},
"initials": &graphql.Field{Type: graphql.String},
},
})
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},
"subtitle": &graphql.Field{Type: graphql.String},
"edition": &graphql.Field{Type: graphql.String},
"author": &graphql.Field{
Type: authorType,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
name := "Ursula K. Le Guin"
// A map source: keys are field names; a func() interface{}
// value is called.
return map[string]interface{}{
"name": name,
"initials": func() interface{} {
var initials []string
for _, part := range strings.Fields(name) {
initials = append(initials, part[:1])
}
return strings.Join(initials, "")
},
}, nil
},
},
},
})
shelfType := graphql.NewObject(graphql.ObjectConfig{
Name: "Shelf",
Fields: graphql.Fields{
"count": &graphql.Field{Type: graphql.Int},
"totalPages": &graphql.Field{Type: graphql.Int},
},
})
queryType := graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"books": &graphql.Field{
Type: graphql.NewList(bookType),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return books, nil
},
},
"shelf": &graphql.Field{
Type: shelfType,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return Shelf{Books: books}, nil
},
},
},
})
return graphql.NewSchema(graphql.SchemaConfig{
Query: queryType,
// Strict serialization unwraps sql.NullString and other driver.Valuer
// values; see the Serialization option.
Serialization: graphql.SerializationConfig{Mode: graphql.SerializationStrict},
})
}
func main() {
schema, err := newSchema()
if err != nil {
log.Fatal(err)
}
query := `{
books { id title pages subtitle edition author { name initials } }
shelf { count totalPages }
}`
result := graphql.Do(graphql.Params{Schema: schema, RequestString: query})
out, _ := json.MarshalIndent(result, "", " ")
fmt.Println(string(out))
}Only author and the root fields have resolvers. Running the program prints:
{
"data": {
"books": [
{
"author": {
"initials": "UKLG",
"name": "Ursula K. Le Guin"
},
"edition": "first",
"id": "1",
"pages": 183,
"subtitle": null,
"title": "A Wizard of Earthsea"
},
{
"author": {
"initials": "UKLG",
"name": "Ursula K. Le Guin"
},
"edition": null,
"id": "2",
"pages": 163,
"subtitle": "Earthsea, book two",
"title": "The Tombs of Atuan"
}
],
"shelf": {
"count": 2,
"totalPages": 346
}
}
}