Skip to content
Resolve functions

Resolve functions

A resolve function has the type graphql.FieldResolveFn:

type FieldResolveFn func(p graphql.ResolveParams) (interface{}, error)

It receives everything about the field being resolved in p, and returns the field’s value and an error. This page adds resolvers to a small catalogue; the complete program is at the end.

ResolveParams

FieldContent
SourceThe value returned for the parent object. On a root field, the RootObject given to graphql.Do, or an empty map[string]interface{} when none is given.
ArgsThe field’s arguments, coerced to Go values. See Arguments.
InfoA graphql.ResolveInfo describing where the field is in the request.
ContextThe context.Context given to graphql.Do, for cancellation and request-scoped values.

p.ArgumentState(name, ...) tells whether the request gave an argument, gave it as null or left it out; see Null and omitted arguments.

A field without Resolve uses the default resolver, which reads the value from Source; its lookup rules are in Resolving a field. In the example, id and title of Book come from the struct that way.

A resolver usually starts by asserting the parent’s Go type:

func resolveAuthor(p graphql.ResolveParams) (interface{}, error) {
	return authorNames[p.Source.(*Book).AuthorID], nil
}

Typed arguments and sources

graphql.ArgsAs and graphql.SourceAs (v0.14.0) replace the type assertions on p.Args and p.Source with a struct and an error:

type BookArgs struct {
	ID string `graphql:"id"`
}

func resolveBook(p graphql.ResolveParams) (interface{}, error) {
	args, err := graphql.ArgsAs[BookArgs](p)
	if err != nil {
		return nil, err
	}
	book, ok := books[args.ID]
	if !ok {
		return nil, fmt.Errorf("no book with ID %s", args.ID)
	}
	return book, nil
}

func resolveAuthor(p graphql.ResolveParams) (interface{}, error) {
	book, err := graphql.SourceAs[*Book](p)
	if err != nil {
		return nil, err
	}
	return authorNames[book.AuthorID], nil
}

ArgsAs fills a struct from p.Args:

  • A field takes the argument named by its graphql tag, else by its json tag, else the one that matches its name without regard to case, which are the names the default resolver reads, so one struct can serve as input and as output. A tag of - skips the field, and the fields of embedded structs count as fields of the struct. A field without a tag whose name matches more than one argument, such as id and ID, is an error; give it a tag.
  • An input object decodes into a nested struct, and a list into a slice.
  • A value is converted to the field’s type when it fits: an Int argument fills an int64 or a uint8, a String or an enum value fills a named string type. A number that overflows, or a value of another kind, is an error that names the value, such as graphql: cannot decode argument "input.items[1].quantity": string does not fit int.
  • A value that fits neither way is decoded through a method of the field’s type (v0.15.0): Scan of a sql.Scanner, as for sql.NullString or a soft-delete timestamp, and then, for a string, UnmarshalText of an encoding.TextUnmarshaler, as for a UUID or a time.Time. An error or a panic of the method is a decode error that names the argument, such as graphql: cannot decode argument "count": string into sql.NullInt64: .... json.Unmarshaler is not used. For a custom scalar, the value is what its ParseValue returns for a variable and its ParseLiteral returns for a literal, so both must fit the field by one of these rules.
  • An argument without a field is ignored. An argument that p.Args does not hold, or holds as nil, leaves its field at the zero value: an omitted argument with a DefaultValue fills the field with the default. Use a pointer when nil should mean “no value”, or graphql.Optional[T] to tell null from omitted, as in Null and omitted arguments.

SourceAs returns p.Source as the type asked for, and an error instead of a panic when it is something else, nil or a nil pointer. It accepts a *Book where a Book is asked for, and the other way around.

Both work on a ResolveParams built by hand, so resolvers that use them are tested like any other; see Testing resolvers.

Typed fields

graphql.TypedField (v0.14.0) builds a field whose resolver receives the source and the arguments already typed, and returns a Go type instead of interface{}:

"book": graphql.TypedField(graphql.TypedFieldConfig[any, BookArgs, *Book]{
	Type: bookType,
	Args: graphql.FieldConfigArgument{
		"id": &graphql.ArgumentConfig{Type: graphql.NewNonNull(graphql.ID)},
	},
	Resolve: func(p graphql.TypedParams[any, BookArgs]) (*Book, error) {
		book, ok := books[p.Args.ID]
		if !ok {
			return nil, fmt.Errorf("no book with ID %s", p.Args.ID)
		}
		return book, nil
	},
}),

"author": graphql.TypedField(graphql.TypedFieldConfig[*Book, graphql.NoArgs, string]{
	Type: graphql.String,
	Resolve: func(p graphql.TypedParams[*Book, graphql.NoArgs]) (string, error) {
		return authorNames[p.Source.AuthorID], nil
	},
}),

The three type parameters are the Go type of the source, the struct for the arguments and the type the resolver returns. any accepts every source, as on a root field, and graphql.NoArgs is for a field without arguments. TypedField returns an ordinary *graphql.Field, so typed and untyped fields live in the same graphql.Fields, and a codebase can move one field at a time.

TypedParams has Source and Args with those types, Context and Info as in ResolveParams, and the original ResolveParams in Params, for p.Params.ArgumentState or a helper that takes one. The source is read as by SourceAs and the arguments as by ArgsAs: a source of another type is a field error, not a panic. When the resolver returns an error, the field is null, whatever value it returns with it.

The arguments struct is checked against Args when the schema is built. graphql.NewSchema returns an error when a field of the struct has no argument, which catches a misspelled tag, or has a type that can never hold the argument’s value, in nested input objects and lists too:

Query.book: field ID of main.BookArgs has type int, which cannot hold argument "id" of type ID!

An argument without a field in the struct is fine, and the value of a custom scalar is not checked, since the schema does not know its Go type. Neither is a field whose type has a Scan or UnmarshalText method, for a scalar or enum argument, since what the method accepts is only known when it runs. The type the resolver returns is checked by the compiler against the function only, not against the field’s Type.

ResolveInfo

p.Info describes the field within the request:

FieldUse
FieldNameThe name of the field in the schema, also when the query gives it an alias.
PathWhere the value goes in the response. Path.AsArray() returns it as a slice of response keys (aliases included) and list indexes, such as [books 0 title].
ParentTypeThe object type the field belongs to.
ReturnTypeThe field’s type, with its list and non-null wrappers.
FieldASTsThe selections of the field in the query, for reading sub-selections or directives; see Directives.
FragmentsThe fragment definitions of the document, by name.
OperationThe operation being executed, an *ast.OperationDefinition.
VariableValuesThe request’s variables, after coercion.
RootValueThe root value of the request.
SchemaThe schema.

These make it possible to write code that works for any field, such as logging, metrics or authorization, by wrapping resolvers:

func logged(next graphql.FieldResolveFn) graphql.FieldResolveFn {
	return func(p graphql.ResolveParams) (interface{}, error) {
		value, err := next(p)
		fmt.Printf("%v (%s.%s): err=%v\n", p.Info.Path.AsArray(), p.Info.ParentType, p.Info.FieldName, err)
		return value, err
	}
}

Wrap each field’s resolver with it: Resolve: logged(resolveBook). A built-in way to run a chain of functions around every resolver is on the roadmap (#12).

Return values

The value a resolver returns is completed according to the field’s type: a scalar or enum value is serialized, an object value becomes the Source of its fields’ resolvers, and a list is completed item by item. A nil value is null.

A non-nil error becomes a field error. The error’s message is listed in the response’s errors, with the field’s location and path:

func resolveBook(p graphql.ResolveParams) (interface{}, error) {
	id := p.Args["id"].(string)
	book, ok := books[id]
	if !ok {
		return nil, fmt.Errorf("no book with ID %s", id)
	}
	return book, nil
}

The field is null. If the field is nullable, the other fields resolve normally; if it is non-null, the null propagates to the parent, with the limitation described below.

Return either a value or an error. When a resolver returns both, the value stays in the response next to the error, a behaviour inherited from graphql-go/graphql that the specification does not have (#125).

A resolver that panics produces a field error too, so a bug in one resolver does not take down the request:

Panic valueError message
an errorits Error()
a stringthe string
anything elseAn unknown error occurred.

A runtime error, such as an assignment to a nil map, is an error value, so its message reaches the client. Options to report panics to your code and to keep their details out of responses are on the roadmap (#67, #73).

When a non-null field fails, the fields of the same parent that come after it are not resolved, and their errors are not reported (#126).

Testing resolvers

Resolve functions are plain Go functions, and ResolveParams and ResolveInfo are plain structs, so a test can call a resolver directly with only the fields it uses:

func TestResolveBook(t *testing.T) {
	got, err := resolveBook(graphql.ResolveParams{
		Args: map[string]interface{}{"id": "1"},
	})
	if err != nil {
		t.Fatal(err)
	}
	if title := got.(*Book).Title; title != "A Wizard of Earthsea" {
		t.Errorf("got %q", title)
	}
}

Outside execution, p.ArgumentState answers from Args: a key holding nil is ArgumentNull, a missing key is ArgumentOmitted.

Complete program

main.go
package main

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/gql-go/graphql"
)

type Book struct {
	ID       string `json:"id"`
	Title    string `json:"title"`
	AuthorID string `json:"-"`
}

var books = map[string]*Book{
	"1": {ID: "1", Title: "A Wizard of Earthsea", AuthorID: "le-guin"},
}

var authorNames = map[string]string{"le-guin": "Ursula K. Le Guin"}

// resolveBook returns the book with the id argument, or an error.
func resolveBook(p graphql.ResolveParams) (interface{}, error) {
	id := p.Args["id"].(string)
	book, ok := books[id]
	if !ok {
		return nil, fmt.Errorf("no book with ID %s", id)
	}
	return book, nil
}

// resolveAuthor returns the name of the author of the source book.
func resolveAuthor(p graphql.ResolveParams) (interface{}, error) {
	return authorNames[p.Source.(*Book).AuthorID], nil
}

// logged wraps a resolver and prints where in the response it ran.
func logged(next graphql.FieldResolveFn) graphql.FieldResolveFn {
	return func(p graphql.ResolveParams) (interface{}, error) {
		value, err := next(p)
		fmt.Printf("%v (%s.%s): err=%v\n", p.Info.Path.AsArray(), p.Info.ParentType, p.Info.FieldName, err)
		return value, err
	}
}

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)},
			"author": &graphql.Field{Type: graphql.String, Resolve: logged(resolveAuthor)},
		},
	})
	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: logged(resolveBook),
			},
		},
	})
	return graphql.NewSchema(graphql.SchemaConfig{Query: queryType})
}

func main() {
	schema, err := newSchema()
	if err != nil {
		log.Fatal(err)
	}
	query := `{
  found: book(id: "1") { title author }
  missing: book(id: "9") { title }
}`
	result := graphql.Do(graphql.Params{Schema: schema, RequestString: query})
	out, _ := json.MarshalIndent(result, "", "  ")
	fmt.Println(string(out))
}
main_test.go
package main

import (
	"testing"

	"github.com/gql-go/graphql"
)

func TestResolveBook(t *testing.T) {
	got, err := resolveBook(graphql.ResolveParams{
		Args: map[string]interface{}{"id": "1"},
	})
	if err != nil {
		t.Fatal(err)
	}
	if title := got.(*Book).Title; title != "A Wizard of Earthsea" {
		t.Errorf("got %q", title)
	}

	if _, err := resolveBook(graphql.ResolveParams{
		Args: map[string]interface{}{"id": "9"},
	}); err == nil {
		t.Error("want an error for an unknown ID")
	}
}

func TestResolveAuthor(t *testing.T) {
	got, err := resolveAuthor(graphql.ResolveParams{
		Source: &Book{AuthorID: "le-guin"},
	})
	if err != nil || got != "Ursula K. Le Guin" {
		t.Errorf("got %v, %v", got, err)
	}
}

found and missing are aliases of book. Running the program logs each wrapped resolver, with the alias in the path:

[found] (Query.book): err=<nil>
[found author] (Book.author): err=<nil>
[missing] (Query.book): err=no book with ID 9

and prints:

{
  "data": {
    "found": {
      "author": "Ursula K. Le Guin",
      "title": "A Wizard of Earthsea"
    },
    "missing": null
  },
  "errors": [
    {
      "message": "no book with ID 9",
      "locations": [
        {
          "line": 3,
          "column": 3
        }
      ],
      "path": [
        "missing"
      ]
    }
  ]
}
Last updated on