Unlocking the Power of GraphQL: A Journey with Union Types
The Mystery of Union Types
In GraphQL, union types are abstract types that indicate a field can return more than one object type. Think of them as a container that holds multiple types, but doesn’t define specific fields itself.
type PageZone {
id: ID!
components: [Image | Quote | Video]
}
In the example above, the components
field in the PageZone
object is a union type that can return either an Image
, Quote
, or Video
object type.
The Apollo Client Conundrum
The default heuristic fragment matcher in Apollo Client won’t work accurately with union types. To solve this issue, we can use the IntrospectionFragmentMatcher.
import { IntrospectionFragmentMatcher } from '@apollo/client';
const fragmentMatcher = new IntrospectionFragmentMatcher({
// Your schema endpoint
apiUrl: 'https://your-graphql-api.com/graphql',
});
const client = new ApolloClient({
uri: 'https://your-graphql-api.com/graphql',
fragmentMatcher,
});
Setting Up GraphQL Code Generator
To implement the IntrospectionFragmentMatcher, we need to use GraphQL Code Generator. This tool helps us avoid making heuristic queries.
# codegen.yml
schema: https://your-graphql-api.com/graphql
documents: './src/graphql/**/*.graphql'
generates:
./src/generated/introspection.ts:
plugins:
- typescript
- typescript-operations
config:
useDocumentNodes: true
Rendering Query Results
Now that we’ve set up Apollo Client, it’s time to render our query results. In a Nuxt.js application, we can use the v-for
directive to loop over the elements in our query result.
<template>
<div v-for="(component, index) in pageZone.components" :key="index">
<ImageComponent v-if="component.__typename === 'Image'" :image="component" />
<QuoteComponent v-else-if="component.__typename === 'Quote'" :quote="component" />
<VideoComponent v-else-if="component.__typename === 'Video'" :video="component" />
</div>
</template>
The Logic Behind Displaying Data
The core logic behind displaying this data is:
- Looping through the query result
- Looping through the Union type
- Creating “zones” by conditionally displaying components based on the type
This approach can be applied to any frontend, with slight variations in Apollo config directories.
Embracing the Flexibility of Union Types
GraphQL is an incredibly powerful tool that enables us to do a lot. By understanding union types and solving the problem of heuristic queries with Apollo Client, we can unlock the full potential of GraphQL.
Share your experiences and favorite types on Twitter! Tweet now