Skip to content
Custom scalars

Custom scalars

A scalar is a leaf value: it has no fields, and it is written in queries and responses as a single JSON value. The library has the specification’s Int, Float, String, Boolean and ID, plus DateTime. A custom scalar adds another, with your own rules for converting it to and from Go. This page adds a Date scalar to the catalogue; the complete program is at the end.

Built-in scalars

ScalarIn responsesIn p.Args
Inta number in the 32-bit rangeint
Floata numberfloat64
Stringa stringstring
Booleantrue or falsebool
IDa stringstring
DateTimean RFC 3339 string, from a time.Timetime.Time

DateTime is not part of the specification; it is inherited from graphql-go/graphql.

Defining a scalar

graphql.NewScalar takes three functions:

  • Serialize turns the value a resolver returned into the value written in the response.
  • ParseValue turns a value from the request’s variables, as decoded from JSON, into the Go value the resolvers receive.
  • ParseLiteral does the same for a value written in the query, which arrives as an AST node from github.com/gql-go/graphql/language/ast.
const dateLayout = "2006-01-02"

var dateType = graphql.NewScalar(graphql.ScalarConfig{
	Name:        "Date",
	Description: "A calendar date, written as YYYY-MM-DD.",
	Serialize: func(value interface{}) interface{} {
		switch v := value.(type) {
		case time.Time:
			return v.Format(dateLayout)
		case *time.Time:
			return v.Format(dateLayout)
		}
		return nil
	},
	ParseValue: func(value interface{}) interface{} {
		s, ok := value.(string)
		if !ok {
			return nil
		}
		return parseDate(s)
	},
	ParseLiteral: func(valueAST ast.Value) interface{} {
		s, ok := valueAST.(*ast.StringValue)
		if !ok {
			return nil
		}
		return parseDate(s.Value)
	},
})

// parseDate returns a time.Time, or nil when s is not a valid date.
func parseDate(s string) interface{} {
	t, err := time.Parse(dateLayout, s)
	if err != nil {
		return nil
	}
	return t
}

Serialize is required. A scalar used only in responses can leave out the two parse functions; one used in arguments needs both. NewSchema reports a scalar that breaks these rules:

Date must provide "serialize" function. If this custom Scalar is also used as an input type, ensure "parseValue" and "parseLiteral" functions are also provided.
Date must provide both "parseValue" and "parseLiteral" functions.

ParseLiteral receives the node as written: *ast.StringValue for "1968-11-01", *ast.IntValue for 1968, and so on. Accept the kinds that make sense for the scalar and return nil for the others. A null, written in the query or sent in a variable, never reaches ParseLiteral or ParseValue: the library handles it before calling them.

Serializing

Serialize receives exactly what the resolver returned, with no unwrapping: the library does not follow pointers or call driver.Valuer for custom scalars. Handle every Go type your resolvers can return; the example accepts both time.Time and *time.Time. A nil result, including a nil pointer, never reaches Serialize: the field is null before it is called, so Serialize cannot replace a missing value.

When Serialize returns nil for a nullable field, the field is null, without an error. For a non-null field such as Book.published, the null is reported as Cannot return null for non-nullable field Book.published. and moves up to the parent. The Serialization option of the schema (v0.11.0) does not check custom scalars, so this holds in strict mode too. A Serialize that panics produces a field error with the panic’s message, which is the only way to report one today; serialize functions that return an error are on the roadmap (#8).

Parsing input

When ParseValue or ParseLiteral returns nil, the value is invalid, and the request fails validation before any resolver runs:

Argument "date" has invalid value "1969-13-01".
Expected type "Date", found "1969-13-01".

Variable "$d" got invalid value "yesterday".
Expected type "Date", found "yesterday".

A ParseLiteral that panics makes the value invalid in the same way, with the panic’s message after the expected type: Expected type "Date", found "1969-13-01"; month out of range (v0.14.0). When the document skips validation, as with Execute, a panic in a literal argument fails that field with the panic’s message, and the other fields still resolve; a panic in a variable’s default value fails the request with the panic’s message and no data. A ParseValue that panics also fails the request with the panic’s message and no data.

The value they return is what the resolver finds in p.Args, so a resolver can assert the type directly when the argument is non-null, as date: Date! is in the complete program below:

after := p.Args["date"].(time.Time)

For a nullable argument, use the two-value form, after, ok := p.Args["date"].(time.Time): with the Coercion option in spec mode, an explicit null arrives as nil (see Null and omitted arguments).

A scalar without parse functions accepts no literals other than null, but a variable of that type reaches the resolver unchanged, as decoded from JSON. Give a scalar both parse functions if it can appear in arguments.

Complete program

main.go
package main

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

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

const dateLayout = "2006-01-02"

// dateType is a calendar date without a time, written as "YYYY-MM-DD".
var dateType = graphql.NewScalar(graphql.ScalarConfig{
	Name:        "Date",
	Description: "A calendar date, written as YYYY-MM-DD.",
	Serialize: func(value interface{}) interface{} {
		switch v := value.(type) {
		case time.Time:
			return v.Format(dateLayout)
		case *time.Time:
			return v.Format(dateLayout)
		}
		return nil
	},
	ParseValue: func(value interface{}) interface{} {
		s, ok := value.(string)
		if !ok {
			return nil
		}
		return parseDate(s)
	},
	ParseLiteral: func(valueAST ast.Value) interface{} {
		s, ok := valueAST.(*ast.StringValue)
		if !ok {
			return nil
		}
		return parseDate(s.Value)
	},
})

// parseDate returns a time.Time, or nil when s is not a valid date.
func parseDate(s string) interface{} {
	t, err := time.Parse(dateLayout, s)
	if err != nil {
		return nil
	}
	return t
}

type Book struct {
	Title     string    `json:"title"`
	Published time.Time `json:"published"`
}

var books = []*Book{
	{Title: "A Wizard of Earthsea", Published: time.Date(1968, 11, 1, 0, 0, 0, 0, time.UTC)},
	{Title: "The Left Hand of Darkness", Published: time.Date(1969, 3, 1, 0, 0, 0, 0, time.UTC)},
	{Title: "The Dispossessed", Published: time.Date(1974, 5, 1, 0, 0, 0, 0, time.UTC)},
}

func newSchema() (graphql.Schema, error) {
	bookType := graphql.NewObject(graphql.ObjectConfig{
		Name: "Book",
		Fields: graphql.Fields{
			"title":     &graphql.Field{Type: graphql.NewNonNull(graphql.String)},
			"published": &graphql.Field{Type: graphql.NewNonNull(dateType)},
		},
	})

	queryType := graphql.NewObject(graphql.ObjectConfig{
		Name: "Query",
		Fields: graphql.Fields{
			"publishedAfter": &graphql.Field{
				Type: graphql.NewNonNull(graphql.NewList(graphql.NewNonNull(bookType))),
				Args: graphql.FieldConfigArgument{
					"date": &graphql.ArgumentConfig{Type: graphql.NewNonNull(dateType)},
				},
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					after := p.Args["date"].(time.Time)
					var result []*Book
					for _, b := range books {
						if b.Published.After(after) {
							result = append(result, b)
						}
					}
					return result, nil
				},
			},
		},
	})

	return graphql.NewSchema(graphql.SchemaConfig{Query: queryType})
}

func main() {
	schema, err := newSchema()
	if err != nil {
		log.Fatal(err)
	}
	query := `{ publishedAfter(date: "1969-01-01") { title published } }`
	result := graphql.Do(graphql.Params{Schema: schema, RequestString: query})
	out, _ := json.MarshalIndent(result, "", "  ")
	fmt.Println(string(out))
}

Running it prints:

{
  "data": {
    "publishedAfter": [
      {
        "published": "1969-03-01",
        "title": "The Left Hand of Darkness"
      },
      {
        "published": "1974-05-01",
        "title": "The Dispossessed"
      }
    ]
  }
}

The repository has another example in examples/custom-scalar-type. Common scalars such as JSON and Int64 are planned as part of the library (#38).

Last updated on