Why code-first
Your schema is not a file that a tool turns into Go. It is Go: every type,
field and resolver is a value your program builds, with the whole language at
hand. No generator to install, no generated files to commit, nothing to keep in
sync. Write Go, run go build, ship. The
complete program at the end puts it all together.
It is just Go
graphql.NewObject, graphql.Fields and graphql.NewSchema are ordinary
constructors, so the tools you already use to organise code apply to the schema
too:
- A function that returns a type is a reusable piece of schema. A paginated list, a standard set of audit fields or an error union is written once and called wherever it is needed.
- A loop builds fields from data: one field per column, per enum value or per entry in a configuration table.
- A package owns the types of its domain and exports them, and the schema is assembled from those packages like any other Go program.
No template language, no configuration file mapping types to code, no naming conventions to memorize. If you know Go, you already know how to organize your schema.
Skip the generate step
Your schema changes when your code changes, because it is your code. A change
to a type is a change to Go code: go build and go vet check it, and review
shows only the lines you wrote. There is no tool to install, no step to
remember before committing and no generated copy to fall out of sync. A new
contributor clones the repository and runs go test ./....
Schemas that follow your data
Your schema can be built from information that only exists when the program starts or when a request arrives, something a schema fixed at build time cannot do:
- Types derived from database metadata, from a plugin registry or from a feature flag.
- One schema per tenant or per API version, each built by the same function with different input, and chosen per request.
- Types added after the schema exists, with
Schema.AppendType, before the schema serves requests: it is not safe to call while queries run. To change a schema in use, build a new one and switch to it.
graphql.NewSchema checks the result the same way in every case, so a
schema built from data gets the same validation as one written by hand.
Tested like any Go function
A schema is a value and graphql.Do is a function call, so a test can build the
schema, run a query and compare the result, with no HTTP server and no mocks.
Resolvers are plain functions as well, and can be called directly with a
graphql.ResolveParams that the test fills in; see
Resolve functions.
Complete program
The program builds a Book type from a list of columns, wraps it in a page
type with a reusable function, and runs a query against the result.
package main
import (
"encoding/json"
"fmt"
"log"
"github.com/gql-go/graphql"
)
// column describes a field, as it could come from database metadata.
type column struct {
name string
typ graphql.Output
}
// objectFromColumns builds an object type with one field per column. The
// default resolver reads each field from a map source by its name.
func objectFromColumns(name string, columns []column) *graphql.Object {
fields := graphql.Fields{}
for _, c := range columns {
fields[c.name] = &graphql.Field{Type: c.typ}
}
return graphql.NewObject(graphql.ObjectConfig{Name: name, Fields: fields})
}
// pageOf builds a page type for any object type.
func pageOf(item *graphql.Object) *graphql.Object {
return graphql.NewObject(graphql.ObjectConfig{
Name: item.Name() + "Page",
Fields: graphql.Fields{
"items": &graphql.Field{Type: graphql.NewList(item)},
"total": &graphql.Field{Type: graphql.Int},
},
})
}
func main() {
book := objectFromColumns("Book", []column{
{name: "title", typ: graphql.String},
{name: "year", typ: graphql.Int},
})
books := []interface{}{
map[string]interface{}{"title": "The Go Programming Language", "year": 2015},
map[string]interface{}{"title": "Learning GraphQL", "year": 2018},
}
query := graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"books": &graphql.Field{
Type: pageOf(book),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return map[string]interface{}{"items": books, "total": len(books)}, nil
},
},
},
})
schema, err := graphql.NewSchema(graphql.SchemaConfig{Query: query})
if err != nil {
log.Fatalf("failed to create schema: %v", err)
}
r := graphql.Do(graphql.Params{
Schema: schema,
RequestString: `{ books { total items { title year } } }`,
})
if len(r.Errors) > 0 {
log.Fatalf("failed to execute operation: %+v", r.Errors)
}
rJSON, _ := json.Marshal(r)
fmt.Printf("%s\n", rJSON)
}Running it prints:
{"data":{"books":{"items":[{"title":"The Go Programming Language","year":2015},{"title":"Learning GraphQL","year":2018}],"total":2}}}