97 GraphQL Code Generator and Schema Automation
97 GraphQL Code Generator and Schema Automation: Accelerating Modern API Development
GraphQL is increasingly becoming the de facto standard in modern API development. It offers more flexible querying than REST and enables front-end and back-end teams to collaborate more effectively. However, the maintainability and scalability of a GraphQL schema can pose their own challenges, especially as the number of types, queries, mutations, and resolvers continues to grow.
In this article, I want to discuss one of the most valuable tools for supporting a GraphQL development workflow, namely GraphQL Code Generator . We will also look at how a code generator can help with automation, reduce boilerplate, improve type safety, and speed up time-to-market through real-world examples and process flow diagrams.
The Challenges of GraphQL Schema Development
When we build a GraphQL API for a real-world service, the process often looks something like this:
flowchart TD
A[Tulis skema GraphQL] --> B[Tulis resolver (manual)]
B --> C[Test query]
C --> D[Perbaiki skema & resolver jika perlu]
Every schema change often requires engineers to update resolvers, TypeScript typings, or generate documentation manually. This is prone to inconsistencies. For example, when there is a change to the schema (type User { ... }), an engineer might forget to update the resolver and the related types, causing a runtime error.
The Solution: Automation with GraphQL Code Generator
GraphQL Code Generator
(@graphql-codegen/cli) is here to solve this problem.
What Is GraphQL Code Generator?
Simply put, GraphQL Code Generator is an open-source tool that can generate static code based on the GraphQL schema and the operations (queries/mutations) we create. The output can take the form of TypeScript typings, resolver skeletons, React hooks, and even API documentation.
Key benefits:
- Type Safety: No more mistyping properties when accessing a response.
- Reduced Boilerplate: Much of the code is generated automatically, with less manual copy-paste.
- Consistency: The schema, client code, and resolvers always stay in sync.
- Productivity: The time it takes to develop new features becomes much shorter.
Case Study: Generating TypeScript Types & React Hooks
Let’s try simulating a simple project.
The GraphQL Schema
Suppose we have the following schema (for example, in a file named schema.graphql):
1type User {
2 id: ID!
3 name: String!
4 email: String!
5}
6
7type Query {
8 users: [User!]!
9 user(id: ID!): User
10}A GraphQL Query for the Frontend (src/queries/getUsers.graphql)
1query GetUsers {
2 users {
3 id
4 name
5 email
6 }
7}Installing GraphQL Code Generator
Install the dependencies in a Node.js-based project:
1npm install @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typescript-react-apollo --save-devOr via Yarn:
1yarn add @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typescript-react-apollo --devConfiguration: codegen.yml
Create a config file named codegen.yml:
1schema: ./schema.graphql
2documents: ./src/queries/**/*.graphql
3generates:
4 ./src/generated/graphql.tsx:
5 plugins:
6 - typescript
7 - typescript-operations
8 - typescript-react-apolloThe Autogen Process: Workflow Diagram
sequenceDiagram
autonumber
User->>CodeGenCLI: run `graphql-codegen`
CodeGenCLI->>Schema: Baca file schema.graphql
CodeGenCLI->>Documents: Baca file query .graphql
CodeGenCLI->>TypeScriptPlugin: Generate typings dari schema
CodeGenCLI->>ReactApolloPlugin: Generate custom React hooks
CodeGenCLI->>User: Output file src/generated/graphql.tsx
Running the Generator
1npx graphql-codegenOnce it runs, we get an auto-generated output file, for example src/generated/graphql.tsx.
Examples of the Generated Output
Automatic Typings
1export type User = {
2 __typename?: 'User';
3 id: string;
4 name: string;
5 email: string;
6};
7
8export type GetUsersQuery = {
9 users: Array<User>;
10};Automatic React Hook
1export function useGetUsersQuery(baseOptions?: Apollo.QueryHookOptions<GetUsersQuery>) {
2 return Apollo.useQuery<GetUsersQuery, GetUsersQueryVariables>(GetUsersDocument, baseOptions);
3}useGetUsersQuery() and get full autocomplete and type safety. There is no longer any need to manually write the response types, which is error-prone.Value Comparison Table
| Feature | Manual | With Codegen |
|---|---|---|
| Generate typings | Must be written by hand | Automatic from the schema |
| Schema synchronization | Prone to typos, not automatic | Always consistent |
| Create custom hooks | Manual, repetitive | Automatically available per query |
| Maintainability | Complex, high risk | Simple, predictable |
| Scaling to large queries | Error-prone, not reusable | Very easy to reorganize |
Schema Automation for the Server (Backend)
Beyond the client side, GraphQL Code Generator can help backend engineers generate skeleton code for resolvers, for example with the typescript-resolvers plugin:
1 ./src/generated/resolvers-types.ts:
2 plugins:
3 - typescript
4 - typescript-resolversThe output: Every change in the schema automatically updates the interface in TypeScript. For example:
1export interface QueryResolvers<ContextType = any> {
2 users: Resolver<Array<User>, {}, ContextType>;
3 user: Resolver<User, { id: string }, ContextType>;
4}Errors caused by a mismatched return type from a resolver can be drastically reduced! Resolvers also get auto-typed, reducing runtime bugs.
Schema Automation in a Real-World Project
Most engineering teams at unicorns/startups now use pipelines like the following:
flowchart TD
Dev[Update schema.graphql] --> CI[CI/CD Pipeline]
CI -->|auto-run| Codegen[GraphQL Codegen]
Codegen --> Commit[Update commit typings]
Commit --> Deploy[Deploy]
With this pattern, the schema and the entire code base stay up to date automatically, without disrupting the development flow.
Conclusion
GraphQL Code Generator is one of the essential tools for engineers building modern APIs. It brings automation to the generation of types, hooks, resolver skeletons, and even documentation, so that we can:
- Increase development speed
- Reduce human error
- Guarantee consistency between client and server
Don’t be afraid to give it a try! In large teams, schema automation not only improves code quality but also helps build a healthy engineering culture.
Are you already using codegen in your GraphQL projects? Share your experiences or the challenges you’ve run into in the comments!