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,
},
})| Mode | Response | Reports |
|---|---|---|
SerializationLenient (default) | As in graphql-go/graphql. | Nothing. |
SerializationReport | The same as lenient. | Every value that strict mode would serialize differently, through OnInvalidValue. |
SerializationStrict | As 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 returns | Field | Lenient | Strict | Report kind |
|---|---|---|---|---|
"12.50" | Int | 12 | field error: Int cannot represent non-integer value: "12.50" | invalid |
int64(3000000000) | Int | null | field error: Int cannot represent non 32-bit signed integer value: 3000000000 | invalid |
math.NaN() | Float | null | field error: Float cannot represent non numeric value: NaN | invalid |
a time.Time | String | "1968-11-01 12:00:00 +0000 UTC" | "1968-11-01T12:00:00Z" | corrected |
sql.NullInt64{Int64: 5, Valid: true} | Int | null | 5 | corrected |
sql.NullString{String: "s", Valid: true} | String | "{s true}" | "s" | corrected |
an unknown enum value, or int64(1) for an int value | enum | null | field error: Enum "Color" cannot represent value: 9 | invalid |
the plain int 1 for a value Color(1) | enum | null | "RED" | corrected |
"12", 3, 1 | Int, String, Boolean | 12, "3", true | the same | none |
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:
| Field | Content |
|---|---|
Kind | SerializationInvalid: strict mode returns a field error. SerializationCorrected: strict mode returns another value. |
Path, ParentType, FieldName | Where the value is: the response path, and the field. |
Type | The scalar or enum. |
Value | What the resolver returned. |
Message | The graphql-js message for invalid values; the change for corrected ones. |
LenientResult, StrictResult | What 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:
- Run with
SerializationReport. Responses do not change. - Collect the events.
invalidones point at resolvers that return a value of the wrong type;correctedones show values whose response will change. - Fix the resolvers, or confirm that clients accept the corrected values.
- Switch to
SerializationStrictonce 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"
]
}
]
}