Interfaces and unions
Interfaces and unions are abstract types: a field of one of these types returns values of several object types, and the client picks the fields it wants from each with fragments. This page extends the catalogue from Objects and fields with films; the complete program is at the end.
- An interface declares fields that every object implementing it must have.
Mediadeclaresidandtitle, andBookandFilmimplement it. - A union is a set of object types with no fields in common required.
SearchResultis either aBookor anAuthor.
Interfaces
graphql.NewInterface declares the shared fields and a ResolveType function
that tells the executor which object type a value is:
var bookType, filmType *graphql.Object
mediaType := graphql.NewInterface(graphql.InterfaceConfig{
Name: "Media",
Fields: graphql.Fields{
"id": &graphql.Field{Type: graphql.NewNonNull(graphql.ID)},
"title": &graphql.Field{Type: graphql.NewNonNull(graphql.String)},
},
ResolveType: func(p graphql.ResolveTypeParams) *graphql.Object {
switch p.Value.(type) {
case *Book:
return bookType
case *Film:
return filmType
}
return nil
},
})An object implements the interface by listing it in Interfaces and declaring
each of its fields, with the interface’s arguments and the same type or a more
specific one (a String! field satisfies a String field of the interface):
filmType = graphql.NewObject(graphql.ObjectConfig{
Name: "Film",
Interfaces: []*graphql.Interface{mediaType},
Fields: graphql.Fields{
"id": &graphql.Field{Type: graphql.NewNonNull(graphql.ID)},
"title": &graphql.Field{Type: graphql.NewNonNull(graphql.String)},
"minutes": &graphql.Field{Type: graphql.Int},
},
})graphql.NewSchema checks that every implementation provides the interface’s
fields with compatible types, and reports the first mismatch:
"Media" expects field "title" but "Film" does not provide it.
Media.title expects type "String!" but Film.title provides type "String".The fields of an interface only declare the contract. The values come from the
fields of the object type that ResolveType picked: a Resolve on an interface
field is not used, so put resolvers on the objects.
Unions
graphql.NewUnion lists its member types, which must be objects, and has the same
ResolveType:
searchResultType := graphql.NewUnion(graphql.UnionConfig{
Name: "SearchResult",
Types: []*graphql.Object{bookType, authorType},
ResolveType: func(p graphql.ResolveTypeParams) *graphql.Object {
switch p.Value.(type) {
case *Book:
return bookType
case *Author:
return authorType
}
return nil
},
})A union has no fields of its own; the client asks for fields inside fragments on
each member. When a member type refers back to the union, pass the members as a
graphql.UnionTypesThunk, as with FieldsThunk for fields.
Choosing the object type
For each value of an interface or union field, the executor needs an object type. It asks, in this order:
The abstract type’s
ResolveType, if it has one.p.Valueis the value the resolver returned;p.Contextandp.Infoare also available.Otherwise, the
IsTypeOffunction of each possible object type, until one returnstrue:bookType := graphql.NewObject(graphql.ObjectConfig{ Name: "Book", Interfaces: []*graphql.Interface{mediaType}, IsTypeOf: func(p graphql.IsTypeOfParams) bool { _, ok := p.Value.(*Book) return ok }, Fields: graphql.Fields{ /* ... */ }, })
ResolveType keeps the decision in one place; IsTypeOf lets each object
recognise its own values. When neither gives an answer, including a
ResolveType that returns nil or a type that is not a member, the value
becomes a field error:
Abstract type Media must resolve to an Object type at runtime for field Query.catalogue with value "&{2 Tales from Earthsea 115}", received "<nil>".For a union, NewSchema requires either ResolveType on the union or IsTypeOf
on every member. For an interface it does not check, so an interface with
neither, or a ResolveType that misses a case, only fails when a query returns
such a value. Cover each implementation in a test.
Listing implementations in the schema
NewSchema collects the types reachable from the root types through fields and
arguments. An object reached only because it implements an interface is not
found that way: in the example, no field returns Film directly. List such
types in SchemaConfig.Types:
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: queryType,
Types: []graphql.Type{filmType},
})Without it, the schema is built without errors but queries fail:
Runtime Object type "Film" is not a possible type for "Media".
Unknown type "Film".The first error comes from a value that resolves to Film; the second is a
validation error for a query with ... on Film. Union members are listed in
Types of the union, so they are always found.
Querying abstract types
A selection on an interface can ask for the interface’s fields directly. Fields
of a specific type, and every field on a union, go inside an inline fragment
(... on Book) or a named fragment. __typename returns the name of the object
type of each value:
{
catalogue {
__typename
title
... on Book { pages }
... on Film { minutes }
}
search(text: "le guin") {
__typename
... on Book { title }
... on Author { name }
}
}Validation rejects fields that the abstract type does not have, and suggests where they are:
Cannot query field "pages" on type "Media". Did you mean to use an inline fragment on "Book"?Complete program
main.go
package main
import (
"encoding/json"
"fmt"
"log"
"strings"
"github.com/gql-go/graphql"
)
type Author struct {
Name string `json:"name"`
}
type Book struct {
ID string `json:"id"`
Title string `json:"title"`
Pages int `json:"pages"`
Author *Author `json:"author"`
}
type Film struct {
ID string `json:"id"`
Title string `json:"title"`
Minutes int `json:"minutes"`
}
var leGuin = &Author{Name: "Ursula K. Le Guin"}
var catalogue = []interface{}{
&Book{ID: "1", Title: "A Wizard of Earthsea", Pages: 183, Author: leGuin},
&Film{ID: "2", Title: "Tales from Earthsea", Minutes: 115},
}
func newSchema() (graphql.Schema, error) {
var bookType, filmType, authorType *graphql.Object
mediaType := graphql.NewInterface(graphql.InterfaceConfig{
Name: "Media",
Description: "Anything in the catalogue.",
Fields: graphql.Fields{
"id": &graphql.Field{Type: graphql.NewNonNull(graphql.ID)},
"title": &graphql.Field{Type: graphql.NewNonNull(graphql.String)},
},
ResolveType: func(p graphql.ResolveTypeParams) *graphql.Object {
switch p.Value.(type) {
case *Book:
return bookType
case *Film:
return filmType
}
return nil
},
})
authorType = graphql.NewObject(graphql.ObjectConfig{
Name: "Author",
Fields: graphql.Fields{
"name": &graphql.Field{Type: graphql.NewNonNull(graphql.String)},
},
})
bookType = graphql.NewObject(graphql.ObjectConfig{
Name: "Book",
Interfaces: []*graphql.Interface{mediaType},
Fields: graphql.Fields{
"id": &graphql.Field{Type: graphql.NewNonNull(graphql.ID)},
"title": &graphql.Field{Type: graphql.NewNonNull(graphql.String)},
"pages": &graphql.Field{Type: graphql.Int},
"author": &graphql.Field{Type: authorType},
},
})
filmType = graphql.NewObject(graphql.ObjectConfig{
Name: "Film",
Interfaces: []*graphql.Interface{mediaType},
Fields: graphql.Fields{
"id": &graphql.Field{Type: graphql.NewNonNull(graphql.ID)},
"title": &graphql.Field{Type: graphql.NewNonNull(graphql.String)},
"minutes": &graphql.Field{Type: graphql.Int},
},
})
searchResultType := graphql.NewUnion(graphql.UnionConfig{
Name: "SearchResult",
Types: []*graphql.Object{bookType, authorType},
ResolveType: func(p graphql.ResolveTypeParams) *graphql.Object {
switch p.Value.(type) {
case *Book:
return bookType
case *Author:
return authorType
}
return nil
},
})
queryType := graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"catalogue": &graphql.Field{
Type: graphql.NewNonNull(graphql.NewList(graphql.NewNonNull(mediaType))),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return catalogue, nil
},
},
"search": &graphql.Field{
Type: graphql.NewNonNull(graphql.NewList(graphql.NewNonNull(searchResultType))),
Args: graphql.FieldConfigArgument{
"text": &graphql.ArgumentConfig{Type: graphql.NewNonNull(graphql.String)},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
text := strings.ToLower(p.Args["text"].(string))
var results []interface{}
if strings.Contains(strings.ToLower(leGuin.Name), text) {
results = append(results, leGuin)
}
for _, item := range catalogue {
book, ok := item.(*Book)
if !ok {
continue
}
if strings.Contains(strings.ToLower(book.Title), text) ||
strings.Contains(strings.ToLower(book.Author.Name), text) {
results = append(results, book)
}
}
return results, nil
},
},
},
})
return graphql.NewSchema(graphql.SchemaConfig{
Query: queryType,
// Film is only reachable through Media, so it must be listed here.
Types: []graphql.Type{filmType},
})
}
func main() {
schema, err := newSchema()
if err != nil {
log.Fatal(err)
}
query := `{
catalogue {
__typename
title
... on Book { pages }
... on Film { minutes }
}
search(text: "le guin") {
__typename
... on Book { title }
... on Author { name }
}
}`
result := graphql.Do(graphql.Params{Schema: schema, RequestString: query})
out, _ := json.MarshalIndent(result, "", " ")
fmt.Println(string(out))
}Running it prints:
{
"data": {
"catalogue": [
{
"__typename": "Book",
"pages": 183,
"title": "A Wizard of Earthsea"
},
{
"__typename": "Film",
"minutes": 115,
"title": "Tales from Earthsea"
}
],
"search": [
{
"__typename": "Author",
"name": "Ursula K. Le Guin"
},
{
"__typename": "Book",
"title": "A Wizard of Earthsea"
}
]
}
}