Back to Graphql Code Generator

typed-document-node

website/src/pages/plugins/typescript/typed-document-node.mdx

1.17.72.8 KB
Original Source

import { Callout } from '@theguild/components' import { PluginHeader } from '@/components/plugin' import { pluginGetStaticProps } from '@/lib/plugin-get-static-props' export const getStaticProps = pluginGetStaticProps(__filename, { hasOperationsNote: true })

<Callout> This plugin is meant to be used for low-level use cases or as building block for presets.

For building a GraphQL client application we recommend using the client-preset. </Callout>

<PluginHeader />

These plugins generate a ready-to-use TypedDocumentNode (a combination of pre-compiled DocumentNode and the TypeScript signature it represents).

With the typed-document-node plugin you no longer need to reconfigure, and install different GraphQL Code Generator plugins to manage all your GraphQL client hooks. Generate a single TypedDocumentNode and pass it to your GraphQL client of choice.

This plugin also generates less boilerplate code for your GraphQL operations.

<Callout> Watch [Episode #41 of `graphql.wtf`](https://graphql.wtf/episodes/41-typed-document-node) for a quick introduction to using this plugin with GraphQL Code Generator: </Callout> <iframe src="https://youtube.com/embed/cYIhx8dusa4" title="Typed Document Node with GraphQL Code Generator" />

Usage example

ts
import type { CodegenConfig } from '@graphql-codegen/cli'

const config: CodegenConfig = {
  schema: 'SCHEMA_FILE_OR_ENDPOINT_HERE',
  documents: './src/**/*.graphql',
  generates: {
    './src/graphql-operations.ts': {
      plugins: ['typescript', 'typescript-operations', 'typed-document-node']
    }
  }
}
export default config

The example about will generate TypedDocumentNode with the needed types built-in, for example:

ts
// Represents the variables type of the operation - generated by `typescript` + `typescript-operations` plugins
export type RatesQueryVariables = Exact<{
  currency: Scalars['String'];
}>;

// Represents the result type of the operation - generated by `typescript` + `typescript-operations` plugins
export type RatesQuery = (
  { __typename?: 'Query' }
  & {
  rates?: Maybe<Array<Maybe<(
    { __typename?: 'ExchangeRate' }
    & Pick<ExchangeRate, 'currency' | 'rate'>
    )>>>
}
  )

// Generated by this plugin - creates a pre-compiled `DocumentNode` and passes result type and variables type as generics
export const ratesQuery: TypedDocumentNode<RatesQuery, RatesQueryVariables> = {
  kind: 'Document',
  definitions: [
    {
      kind: 'OperationDefinition',
      operation: 'query',
      name: { ... }
    }
  ]
}

<Callout>This plugin also requires typescript and typescript-operations.</Callout>

For information about the setup and usage of TypedDocumentNode, please refer to the library's documentation.