This is a very basic and rough React Typescript example project on how to implement multiple Apollo Clients with GraphQL Code Generator and without the usage of any additional packages.
GraphQL is all about a single endpoint, but what if you have to implement something like a third party API and you still want to keep the advantages of GraphQL Code Generator which make your life so much easier?
Well, here we go:
This example implements three different Apollo Clients for the following public GraphQL APIs:
GraphQL Code Generator is used to generate the typings, hooks and schemas. The different APIs use their own code generator configuration files:
- SpaceX:
spacexConfig.ts
- Star Wars:
starWarsConfig.ts
- Countries:
countriesConfig.ts
They generate the following file types for all APIs:
<apiName>.ts
containing Typescript types and react hooks for the queries:<apiName>.schema.json
containing the GraphQL schema used only for IDE autocompletion:
The differentiation between the APIs is very important to not run into any type duplications or other potential conflicts. Additionally this allows for API specific autocompletion and hooks for the queries.
For the automatically generated query hooks, this is achieved by adding specific client names to the code generator config files (except for the default API) and by using custom Apollo hooks (CustomApolloHooks.ts
) which only add the respective Apollo Client to the hook.
In the end the generated hooks for the queries already include a reference to the API specific Apollo Client and you can just use it in your React components, like
use<QueryName>Query()
. This hook returns an object containing for example: data
, error
and loading
.
This is achieved by using suffixes in the GraphQL filenames, e.g. <filename>.sw.graphql
or <filename>.countries.graphql
. The default API (in this case SpaceX) doesn't need any additional suffix and the files can just be named <filename>.graphql
.
The connection between certain filenames and schemas is specified in .graphqlrc.json
- Make sure you have a GraphQL extension for your IDE installed to be able to use autocompletion
- Clone this respository
- Navigate to the directory
- Install packages with
npm i
- Run the application with
npm start
This will run the scripts update-graphql:spacex
, update-graphql:starwars
and update-graphql:countries
which generate the aforementioned files for types, hooks and schemas.
Will also run the graphql-update
script in addition to npm run serve
Some very basic tests have been added to ensure that mocking of queries is also working.