Configuration
You should be familiar with React, Apollo Client, and GraphQL Code Generator as a prerequisite. If you have never used them, you will need to read their documentation first.
Configration for Nau
First, add @kazekyo/nau-graphql-codegen-preset
to your codegen.yml
.
schema: http://localhost:4000/graphql
# Do not use the root document. For example, do not write `documents: src/**/*.graphql` this line.
generates:
src/generated/graphql.ts:
preset: '@kazekyo/nau-graphql-codegen-preset'
presetConfig:
generateTypeScriptCode: true
documents:
- src/**/*.tsx
- src/**/*.graphql
plugins:
- typescript
- typescript-operations
- typed-document-node
src/generated/introspection-result.json:
plugins:
- fragment-matcher
As above, you will need to add this preset to processes that read documents
and use it. In most cases, that means you add the preset to processes of generating files that output TypeScript code.
We recommend not using root documents
. It means that you should not write the following:
schema: http://localhost:4000/graphql
documents:
- src/**/*.tsx
- src/**/*.graphql
generates:
# ...
Using root documents
requires using the preset in all file generation process to parse directives provided by Nau.
Run GraphQL Code Generator.
yarn graphql-codegen
And Configure your cache settings for Apollo Client. Import and use withCacheUpdater
from the generated file, and also use some functions of @kazekyo/nau
.
import { ApolloClient, ApolloProvider, from, HttpLink, InMemoryCache, split } from '@apollo/client';
import { WebSocketLink } from '@apollo/client/link/ws';
import { createCacheUpdaterLink, isSubscriptionOperation } from '@kazekyo/nau';
import { withCacheUpdater } from './generated/graphql';
import introspectionResult from './generated/introspection-result.json';
const wsLink = new WebSocketLink({
uri: 'ws://localhost:4000/subscriptions',
options: {
reconnect: true,
},
});
const httpLink = new HttpLink({ uri: 'http://localhost:4000/graphql' });
const cacheUpdaterLink = createCacheUpdaterLink();
const splitLink = split(
({ query }) => isSubscriptionOperation(query),
from([cacheUpdaterLink, wsLink]),
from([cacheUpdaterLink, httpLink]),
);
const client = new ApolloClient({
cache: new InMemoryCache({
addTypename: true, // Do not set false
possibleTypes: introspectionResult.possibleTypes,
typePolicies: withCacheUpdater({}),
}),
link: splitLink,
});
That's it for the configuration! If you want to set up your IDE, see also here.