Code Generation
GraphQL code generation process and client-side type safety.
Overview
The project uses @graphql-codegen/cli to generate TypeScript types and client hooks from the GraphQL schema. The generated code provides compile-time type safety for all GraphQL operations.
Source and output
| Component | Location |
|---|---|
| Schema source | graphql-api/lib/schema/index.ts |
| Generated types | packages/graphql-types/src/index.ts |
| Codegen config | packages/graphql-types/src/codegen.ts |
| Shared fragments | packages/graphql-types/graphql/fragments/*.graphql |
Client-specific outputs are generated for:
booking-web/gql/index.tsx— React Apollo hooksbooking-web/gql/gql-request.ts— graphql-request typed client
Running codegen
From the monorepo root:
pnpm codegen
This step is mandatory after creating or modifying any .graphql file. Skipping it will cause import errors and build failures.
File organisation rules
GraphQL operations must be defined in separate .graphql files — never as inline gql template literals.
gql/
├── mutations/
│ └── WorkstreamUpsert.graphql
├── queries/
│ └── ProductList.graphql
└── fragments/
└── ProductFields.graphql
File naming
- Use PascalCase for file names:
WorkstreamUpsert.graphql,ProductList.graphql. - Operation names must match the file name (without extension).
Example
# In gql/mutations/WorkstreamUpsert.graphql
mutation WorkstreamUpsert($input: WorkstreamUpsertInput) {
workstreamUpsert(input: $input) {
id
name
}
}
Importing generated types
Always import from the local gql directory — never from @apollo/client:
// Correct
// Incorrect — do not use
import { gql } from "@apollo/client";
import { WorkstreamUpsertDocument, WorkstreamUpsertMutation, WorkstreamUpsertMutationVariables } from "../../gql";
Using generated hooks
import { WorkstreamUpsertDocument, WorkstreamUpsertMutation, WorkstreamUpsertMutationVariables } from "../../gql";
export const useWorkstreamUpsert = () => {
const [mutate, { loading, error }] = useMutation<WorkstreamUpsertMutation, WorkstreamUpsertMutationVariables>(
WorkstreamUpsertDocument
);
return { mutate, loading, error };
};
Migrating from inline GraphQL
- Extract the GraphQL operation from the TypeScript file.
- Create a new
.graphqlfile with the operation. - Run
pnpm codegento generate types. - Update imports to use generated types from the
gqldirectory. - Remove the inline
gqlimport and template literal. - Verify the functionality works correctly.
Troubleshooting
Import errors after adding a .graphql file: Run pnpm codegen — the generated types are missing.
Build failures: Verify the .graphql file exists in the correct directory, the operation name matches the filename, and pnpm codegen has been run.