Easy GraphQL Union Types With Apollo Client V2

Quick JS setup with the Introspection Fragment Matcher

Julio Gudiño
Salesloft Engineering
4 min readJun 2, 2020

--

Photo by Daniele Levis Pelusi on Unsplash

Welcome fellow GQL-head! I’m Juls, a Senior UI Engineer @ SalesLoft. I’ve had the chance to work on and maintain a GraphQL API for a couple of years now. GQL and Apollo have been two of my favorite parts about our stack, and it was only recently that I had the chance to implement union types. We needed a playlists feature with two different types of items. I knew this was possible with GraphQL, but I ended up running around in circles for a while before finding the most direct approach. Hopefully this will help you get up and running with union types super fast.

The Catch

When doing union types in GraphQL + Apollo for the first time, your browser will throw an error like the following:

This happens because Apollo Client does not know what your schema looks like. Normally, this isn’t an issue because most queries return one single type. For union types, we need to create the client cache using the Introspection Fragment Matcher, which helps Apollo Client tell an apple from an orange in a fruit basket.

The Apollo Docs suggest querying your schema from your client using a fetch, but the truth is, the Apollo Client only really needs to know about your union type. We are going to take a shortcut, which greatly simplifies union type implementation.

The Solution

Let’s start all the way from the beginning for those figuring the entire endeavor out:

  1. Server: Creating a union type
  2. Server: Resolving a union type
  3. Client: Querying a union type
  4. Client: Resolving a union type in Apollo Client v2
  5. Client: Resolving a union type in Apollo Client v3 (in beta)

Before we get started, a quick thought about using graphql-tag (or .graphql files) VS. the graphql module. If you very recently started your GraphQL project, do your project a favor and take the template string path to simplicity. Take a look at the same type declared with each approach:

The cleanliness and clarity of the tag approach speaks for itself. We’ll use that for our examples.

1. Server: Creating a union type

A union type is like a switch between two existing types in your schema. In our example, a PlaylistItem is either a Recording or a Clip. In your types declaration file, add a union type like this:

2. Server: Resolving a union type

Your GraphQL API needs some logic to figure out what type it is dealing with. For every PlaylistItem returned by the getPlaylistItems query, GraphQL will run the __resolveType function to check if an object is a Recording or a Clip. Since the Clip must have a recordingId property, we can use that to resolve our union type. This is what our type resolver looks like in our resolvers file:

3. Client: Querying a union type

Using fragments makes querying union types very easy. Create a .js file for your query and declare what you want to return for each type using … on Type:

Your query is now ready for use: useQuery(GET_PLAYLIST_ITEMS). We’re almost there!

4. Client: Resolving a union type in Apollo Client V2

The following introspection query result will help Apollo Client differentiate between types. You can query your entire schema using graphiql or other tools. The only info the client really needs is your union type, so create a .json file and add the following:

Now pull in your schema information into the Introspection Fragment Matcher:

You should now see a healthy query response with your two types available!

5. Client: Resolving a union type in Apollo Client V3

Union types with V2 are a little bit annoying and takes some time to figure out. The lovely peeps at Apollo already have a much simpler way to achieve this in the oven (and got rid of the fragment matchers too!). Union types will be a breeze in v3:

Final Remarks

I hope this helped clarify union types and get you closer to achieving them in your project or application. This is definitely the shortest path to success until v3 is out and about, which should be soonish since the beta has already been around for a couple of months. Union types can be easy, and will get even easier with V3 quite soon.

Share what you’re building with GraphQL in the comments. Thanks for reading and long live GraphQL ❤.

--

--