Unions

Intermediate · 7 min

Model a field that can return one of several unrelated object types with a GraphQL union, query it with inline fragments, and use unions for result types.

Before thisObject types and fieldsInterfaces

Ben Awad · 7 min

Unions

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Ben AwadReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A union such as union SearchResult = Book | Author says a field returns exactly one of the listed object types, which share no required fields.
  • A union has no fields of its own, so every field you select except __typename must sit inside an inline fragment on a member type.
  • Only object types can be members of a union; an interface or scalar in the list makes the schema invalid.
  • The server needs a way to name the concrete type of each value, the same as for interfaces, usually a __typename property or a resolveType function.
  • Unions are a good fit for result types, such as union BookResult = Book | NotFound, where failure is data the client handles.

When there is no shared shape

An interface needs types that share fields. Sometimes they do not. A global search can return books, authors, and publishers. A book has a title. An author has a name. Nothing is common to all three, so there is no useful interface to write.

A union lists the possible types and nothing else:

type Book { title: String! }
type Author { name: String! }

union SearchResult = Book | Author

type Query {
  search(term: String!): [SearchResult!]!
}

A field of type SearchResult returns a Book or an Author, each element on its own.

Querying a union

A union declares no fields, so the server has nothing to promise you directly. You ask for fields type by type:

{
  search(term: "d") {
    ... on Book { title }
    ... on Author { name }
  }
}

On graphql-js 17.1.0, with a resolver returning [{__typename: 'Book', title: 'Dune'}, {__typename: 'Author', name: 'Frank Herbert'}], I got:

{"data":{"search":[{"title":"Dune"},{"name":"Frank Herbert"}]}}

Each element contains just the fields for its type. The client may not know which element is which, so ask for __typename as well:

{ search(term: "d") { __typename ... on Book { title } } }
{"data":{"search":[{"__typename":"Book","title":"Dune"},{"__typename":"Author"}]}}

The author has no title, so you get its __typename only. Two kinds of error appear when you forget the fragment:

{ search(term: "d") { title } }
# Cannot query field "title" on type "SearchResult". Did you mean to use an inline fragment on "Book"?

{ search(term: "d") }
# Field "search" of type "[SearchResult!]!" must have a selection of subfields.

__typename is the only field a union supports without a fragment.

Rules for members

Only object types can be members. This is easy to forget, since interfaces look similar. A union that tries to include one:

type A { a: Int }
interface I { x: Int }
union U = A | I

passes buildSchema but validateSchema reports “Union type U can only include Object types, it cannot include I.” (Same trap as in the interfaces lesson: building a schema from SDL does not check the meaning of it.) If you want a mix of interface and object, create a second object type that implements it or use an interface alone.

Like an interface, a union needs the server to name each value’s concrete type; the same __typename, resolveType and isTypeOf options apply, and the same error appears if there is none.

Results as data

The best use of unions in practice is for expected failures. A missing book is not an exceptional error, it is an answer. You can put that in the schema:

type Book { title: String! }
type NotFound { message: String! }
union BookResult = Book | NotFound

type Query { book(id: ID!): BookResult! }
{ book(id: "9") { __typename ... on Book { title } ... on NotFound { message } } }

With a resolver that returns a NotFound, the response is {"data":{"book":{"__typename":"NotFound","message":"No book 9"}}}. The field is non-null, the failure is typed, and the client is forced by the shape to handle it. Compare that with returning null and an entry in errors, which works but tells the client nothing structured. The trade-offs, and when to use each, are in errors and partial responses and designing mutation inputs and payloads.

Union or interface

Interface Union
Shared fields Required, can be queried directly None
Members Object types that declare implements Object types listed in the union
Add a member later Edit the new type Edit the union itself
Typical use Node, Item, things with a common shape Search results, result types

Adding a member to a union is a change clients must be ready for: code that switches on __typename needs a default branch, or a new type will fall through.

What the video covers

Ben Awad’s “GraphQL Unions Tutorial” is about seven and a half minutes and was published in April 2019. The description links to a code repository for the video. I could not read a transcript, so I cannot describe its walk-through. It predates current server libraries, so the setup may look different from this lesson’s graphql-js examples. Jamie Barton’s shorter video on defining a union with GraphQL Tools is linked as the runner-up. The My Digital Diaries episode used in the previous lessons also has a unions and interfaces chapter.

Where this fits

Unions and interfaces cover types that come out of a server. The last piece of the type system covers what goes in. Next: input types.

Check yourself

  1. 01Why can't you write { search(term: "d") { title } } when search returns a union?

    The union itself has no fields, so the validator asks for an inline fragment on a member type, such as ... on Book { title }.

  2. 02What can you select on a union without a fragment?

    Only __typename, which every abstract type supports.

  3. 03Can an interface be a member of a union?

    No. Union members must be object types, and graphql-js reports that a union can only include object types.

  4. 04How would you model a field that returns either a book or a not-found message?

    As a union of the two object types, such as union BookResult = Book | NotFound, so the client branches on __typename.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark