Setting Up Heuristic Matchers


  1. Fragment Matcher - GraphQL Code Generator
  2. TypeScript - GraphQL Code Generator
  3. Apollo Client - Using fragments

The issue

With Apollo Client, you need to do some extra setup to get Apollo to place nice with heurstics based on unions. If not, it will fail based on a heuristic missing pieces of data.

This results in the error state being thrown by the client.

In order to resolve this, it requires us to install a few pieces of work.


yarn add -D @graphql-codegen/cli @graphql-codegen/fragment-matcher

Add graphql-codegen to npm scripts.

Ensure you are using @apollo/client and drop @apollo/react-hooks as it is included now (see the GitHub issue here).

This also means ensuring imports for the ApolloProvider and other hooks come from @apollo/client.

Setup for Apollo Client

With Apollo Client 3, you'll need to make the following changes to your current file that sets up the client:

import { InMemoryCache, IntrospectionFragmentMatcher, } from 'apollo-cache-inmemory'; // generated by Fragment Matcher plugin import possibleTypes from '../introspection-result'; const cache = new InMemoryCache({ possibleTypes, });


Create a codegen.yml file with some config options:

# codegen.yml schema: http://localhost:7000/performance/api/v2/graphql overwrite: true generates: ./src/introspection-result.ts: plugins: - fragment-matcher

Run yarn codegen to generate the schema while your API is running.

In Action

When all of this is done, you will be able to query your data with no warnings or errors!