Code generation and typed operations

Intermediate · 5 min

Generate TypeScript types and typed document nodes from your schema and operations with GraphQL Code Generator's client preset.

Before thisApollo Client basicsVariables and operation names

Jamie Barton · 5 min

Code generation and typed operations

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Jamie BartonReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A GraphQL operation is a string, so without generation TypeScript cannot know what data or variables it takes.
  • GraphQL Code Generator reads your schema and the operations in your source and emits types for each operation's result and variables.
  • The client preset generates a graphql() function that maps each query string to a typed document node.
  • A result type contains only the fields you selected, not the whole schema type, so it changes when the query changes.
  • Run generation in watch mode in development and in CI, so schema changes break the build instead of production.

A string with no types

A GraphQL operation reaches your code as a template string. TypeScript sees string. When you pass it to useQuery and get back data, the type is any or whatever you guessed in a generic parameter:

const { data } = useQuery<{ books: { id: string; title: string }[] }>(BOOKS);

That annotation is a promise you made by hand. When the schema changes or someone edits the query, nothing checks the promise. You have written the same shape twice, once in GraphQL and once in TypeScript, and they will drift.

GraphQL has an advantage most APIs lack. The schema is machine readable and strongly typed, and every operation can be validated against it. A tool can read both and write the TypeScript for you.

What generation produces

GraphQL Code Generator, graphql-codegen, reads your schema and your operations and emits types. I installed @graphql-codegen/cli 8.0.0 with @graphql-codegen/client-preset 7.0.0 in a scratch project and ran it against a small schema.

// codegen.ts
import type { CodegenConfig } from "@graphql-codegen/cli";

const config: CodegenConfig = {
  schema: "./schema.graphql",
  documents: ["src/**/*.ts"],
  ignoreNoDocuments: true,
  generates: {
    "./src/gql/": { preset: "client", presetConfig: { fragmentMasking: false } },
  },
};
export default config;

An operation in application code goes through the generated graphql function:

import { graphql } from "./gql";

export const BookQuery = graphql(`
  query BookById($id: ID!) {
    book(id: $id) { id title author { name } }
  }
`);

Running npx graphql-codegen --config codegen.ts produced gql.ts, graphql.ts and index.ts in src/gql/. In graphql.ts, the result type for that one operation was:

export type BookByIdQuery = {
  book: { id: string, title: string, author: { name: string } } | null
};

Read it closely. book can be null because the schema field is nullable. author has only name, because that is all the query selected, even though the schema’s Author type also has id and books. The type follows the query, not the schema type. If you later add id to the author selection and regenerate, the type grows by itself. If you misspell titel, generation fails with a validation error before anything runs.

The file also exports BookByIdDocument, a TypedDocumentNode<BookByIdQuery, BookByIdQueryVariables>. The graphql() function maps the query text to that document. Apollo Client, urql and others understand typed document nodes, so useQuery(BookQuery, { variables: { id: "1" } }) infers data and checks that variables has a string id, with no generic annotations. I confirmed the generated types; I did not run useQuery itself, so the inference in a component is docs-derived.

Where the schema comes from

schema can be a local file, as above, or a URL. Pointing it at a running server uses introspection, which is one reason a team might keep introspection on in development, and, if it is disabled in production, commit an SDL file or fetch it from the dev server. See disabling introspection for the other side of that trade-off.

Habits that keep it useful

  • Commit the generated files or generate in CI, but decide which. Either is fine; being half-and-half is not. If you commit them, CI should regenerate and fail on a diff.
  • Use watch mode while developing. graphql-codegen --watch regenerates as you edit.
  • Do not hand-edit generated files. Change the operation or the schema.
  • Treat a schema change as a compile-time event. Removing a field the client queries should fail the build. That is the same gate schema registry checks apply from the server’s side.

The client preset also supports persisted documents, which hash every operation at build time for use with persisted queries. Server-side, a codegen plugin can type your resolvers too, as with the Yoga server from a server with GraphQL Yoga. For TypeScript in the component itself, see typing props, state and hooks.

What the video covers

Jamie Barton’s “The new GraphQL Code Generator Client Preset” is a 4-minute walkthrough from November 2022 on setting up the client preset, which is the setup this lesson uses. It has no chapters, and I could not read a transcript, so I am relying on its title. Because it is four years old and the packages are at much later major versions, copy the shape and verify option names against the current docs. In my run the client preset and the fragmentMasking option still worked with the config shown above. The 2022 runner-up from Lester Fernandez covers typed Apollo operations, but with the plugin-based setup that predates the preset.

Where this fits

This ends the clients group: a hand-written helper, three clients and typed operations. Next the course turns to the server side of the same exchange with authentication and authorization.

Check yourself

  1. 01Why does the type of a query result differ from the schema's type for the same object?

    A query selects some fields, and the generated operation type contains exactly those, so a field you did not ask for is not on the type.

  2. 02What does the graphql() function from the client preset do?

    It takes your query text and returns a typed document node whose result and variables types were generated for that exact operation.

  3. 03What should happen in CI when someone removes a field the client still queries?

    Generation or type checking should fail, because the operation no longer validates against the schema.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark