Skip to content

Serialization

Serialization turns the values your resolvers return into the values of the response, for the built-in scalars (Int, Float, String, Boolean, ID) and for enums. By default it converts whatever it can and returns null for the rest, without an error, which hides mistakes. The Serialization option of the schema (v0.11.0) reports those values, or serializes as the specification says. This page shows the modes and how to move to the strict one; the complete program is at the end.

Modes

schema, err := graphql.NewSchema(graphql.SchemaConfig{
	Query: queryType,
	Serialization: graphql.SerializationConfig{
		Mode:           graphql.SerializationReport,
		OnInvalidValue: logSerialization,
	},
})
ModeResponseReports
SerializationLenient (default)As in graphql-go/graphql.Nothing.
SerializationReportThe same as lenient.Every value that strict mode would serialize differently, through OnInvalidValue.
SerializationStrictAs the specification and graphql-js: a valid serialization is returned, a value without one is a field error.The same values, through OnInvalidValue if set.

What changes

Values measured on master for a few common cases:

Resolver returnsFieldLenientStrictReport kind
"12.50"Int12field error: Int cannot represent non-integer value: "12.50"invalid
int64(3000000000)Intnullfield error: Int cannot represent non 32-bit signed integer value: 3000000000invalid
math.NaN()Floatnullfield error: Float cannot represent non numeric value: NaNinvalid
a time.TimeString"1968-11-01 12:00:00 +0000 UTC""1968-11-01T12:00:00Z"corrected
sql.NullInt64{Int64: 5, Valid: true}Intnull5corrected
sql.NullString{String: "s", Valid: true}String"{s true}""s"corrected
an unknown enum value, or int64(1) for an int valueenumnullfield error: Enum "Color" cannot represent value: 9invalid
the plain int 1 for a value Color(1)enumnull"RED"corrected
"12", 3, 1Int, String, Boolean12, "3", truethe samenone

The last row shows that strict mode keeps the conversions graphql-js also makes, such as a numeric string for Int.

Before checking a value, strict mode unwraps it: a driver.Valuer, such as the sql.Null* types and null.* wrapper types, becomes its value, and for String and ID an encoding.TextMarshaler or fmt.Stringer becomes its text. A nil pointer and an invalid wrapper are null.

Reports

OnInvalidValue receives a graphql.SerializationError for every value that strict mode handles differently from lenient mode:

FieldContent
KindSerializationInvalid: strict mode returns a field error. SerializationCorrected: strict mode returns another value.
Path, ParentType, FieldNameWhere the value is: the response path, and the field.
TypeThe scalar or enum.
ValueWhat the resolver returned.
MessageThe graphql-js message for invalid values; the change for corrected ones.
LenientResult, StrictResultWhat each mode returns. StrictResult is nil for invalid values.

It runs during execution, can be called concurrently, and receives the request’s context, so a logger or metrics client that it uses must be safe for concurrent use.

Moving to strict mode

Strict mode can change responses that clients accept today, as the table above shows: dates change format, some values that came out as null come out right (a valid sql.NullInt64), and values that lenient mode truncated or dropped ("12.50" or an out-of-range number for Int) become field errors. To switch without surprises:

  1. Run with SerializationReport. Responses do not change.
  2. Collect the events. invalid ones point at resolvers that return a value of the wrong type; corrected ones show values whose response will change.
  3. Fix the resolvers, or confirm that clients accept the corrected values.
  4. Switch to SerializationStrict once the remaining events are expected.

Only the built-in scalars and enums are checked. A custom scalar serializes with its own Serialize function in every mode; see Custom scalars. Enum values are matched by identity, and the strict and report modes also convert a value of another Go type with the same kind, as described in Enums.

Complete program

main.go
package main

import (
	"context"
	"database/sql"
	"encoding/json"
	"fmt"
	"log"
	"time"

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

// Book is read from a database: nullable columns arrive as sql.Null* values.
type Book struct {
	Title     string        `json:"title"`
	Published time.Time     `json:"published"`
	Pages     sql.NullInt64 `json:"pages"`
	Rating    string        `json:"rating"` // stored as text, such as "4.5"
}

var book = &Book{
	Title:     "A Wizard of Earthsea",
	Published: time.Date(1968, 11, 1, 0, 0, 0, 0, time.UTC),
	Pages:     sql.NullInt64{Int64: 183, Valid: true},
	Rating:    "4.5",
}

func newSchema(config graphql.SerializationConfig) (graphql.Schema, error) {
	bookType := graphql.NewObject(graphql.ObjectConfig{
		Name: "Book",
		Fields: graphql.Fields{
			"title":     &graphql.Field{Type: graphql.String},
			"published": &graphql.Field{Type: graphql.String},
			"pages":     &graphql.Field{Type: graphql.Int},
			"rating":    &graphql.Field{Type: graphql.Int},
		},
	})
	queryType := graphql.NewObject(graphql.ObjectConfig{
		Name: "Query",
		Fields: graphql.Fields{
			"book": &graphql.Field{
				Type: bookType,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					return book, nil
				},
			},
		},
	})
	return graphql.NewSchema(graphql.SchemaConfig{
		Query:         queryType,
		Serialization: config,
	})
}

func run(config graphql.SerializationConfig) {
	schema, err := newSchema(config)
	if err != nil {
		log.Fatal(err)
	}
	result := graphql.Do(graphql.Params{
		Schema:        schema,
		RequestString: `{ book { title published pages rating } }`,
	})
	out, _ := json.MarshalIndent(result, "", "  ")
	fmt.Println(string(out))
}

func main() {
	// Report mode: the response stays as in lenient mode, and every value
	// that strict mode would handle differently is reported.
	fmt.Println("== report")
	run(graphql.SerializationConfig{
		Mode: graphql.SerializationReport,
		OnInvalidValue: func(ctx context.Context, e graphql.SerializationError) {
			fmt.Printf("%s %s.%s at %v: %s\n", e.Kind, e.ParentType, e.FieldName, e.Path, e.Message)
		},
	})

	// Strict mode: valid values are returned as the specification says, and
	// values without a valid serialization become field errors.
	fmt.Println("== strict")
	run(graphql.SerializationConfig{Mode: graphql.SerializationStrict})
}

The same schema runs in report mode, which logs three values and leaves the response as in lenient mode, and in strict mode, which corrects two values and rejects the third:

== report
corrected Book.published at [book published]: String value changes from "1968-11-01 00:00:00 +0000 UTC" to "1968-11-01T00:00:00Z"
corrected Book.pages at [book pages]: Int value changes from null to 183
invalid Book.rating at [book rating]: Int cannot represent non-integer value: "4.5"
{
  "data": {
    "book": {
      "pages": null,
      "published": "1968-11-01 00:00:00 +0000 UTC",
      "rating": 4,
      "title": "A Wizard of Earthsea"
    }
  }
}
== strict
{
  "data": {
    "book": {
      "pages": 183,
      "published": "1968-11-01T00:00:00Z",
      "rating": null,
      "title": "A Wizard of Earthsea"
    }
  },
  "errors": [
    {
      "message": "Int cannot represent non-integer value: \"4.5\"",
      "locations": [
        {
          "line": 1,
          "column": 32
        }
      ],
      "path": [
        "book",
        "rating"
      ]
    }
  ]
}
Last updated on