Generating TypeScript for GraphQL queries with multiple schema endpoints

I am aware of two tools to generate types (TypeScript, but they also support Flow) for your GraphQL queries:

Both seem to work fine as-is, but I am dealing with the extra challenge of having two separate schema endpoints in my project; that is, some queries you will encounter in the source point to a GraphQL Server A, other points to GraphQL Server B.

Because you can point apollo-tooling only to a single schema, the client:codegen will fail when it encounters a query for any otherm, since it will notice that the types do not match.

graphql-code-generator has the limitations that it only works with separate .graphql files, so it will not find gql tags in your code and extract the queries from there. What you can do here is specify which .graphql files to include, so you can name your files accordingly: .schemaA.graphql, .schemaB.graphql.

Conveniently, it allows you to define multiple targets with their own source files and schema in one config file.

apollo-tooling only allows a single schema/configuration in the config file, but you can just use two separate config files, or, pass options in the CLI. How can we target our gql queries to each schema? We have to use Apollo’s ability to specify the name of the graphql tag used. Usually, this would be:

import gql from 'graphql-tag';

const query = gql`query Foo { bar }`;

Instead we can do:

import gqlA from 'graphql-tag';

const query = gqlA`query Foo { bar }`;

And then we can run the code generator:

apollo client:codegen types/ --target typescript --tagName gqlA --outputFlat

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s