0
0
GraphQLquery~5 mins

Code generation from schema in GraphQL

Choose your learning style9 modes available
Introduction

Code generation from schema helps you create ready-to-use code automatically from your database structure. This saves time and reduces mistakes.

When you want to quickly create code to access your database without writing it all by hand.
When your database schema changes and you need updated code fast.
When you want to ensure your code matches your database structure exactly.
When working in a team to keep everyone using the same database code.
When building apps that need to talk to a database with less manual coding.
Syntax
GraphQL
graphql-codegen --config codegen.yml
You usually run a command line tool with a config file to generate code.
The config file tells the tool what schema to use and what code to create.
Examples
This runs the code generator using the settings in codegen.yml.
GraphQL
graphql-codegen --config codegen.yml
This is a simple config file example telling the generator to use a schema file and create TypeScript code for React Apollo.
GraphQL
schema: ./schema.graphql
documents: ./src/**/*.graphql
generates:
  ./src/generated/graphql.ts:
    plugins:
      - typescript
      - typescript-operations
      - typescript-react-apollo
Sample Program

This example shows how to generate TypeScript code from a simple GraphQL schema with one query.

GraphQL
# 1. Create a schema file named schema.graphql
#
# type Query {
#   hello: String
# }

# 2. Create codegen.yml file:
# schema: ./schema.graphql
# generates:
#   ./generated/graphql.ts:
#     plugins:
#       - typescript

# 3. Run command:
graphql-codegen --config codegen.yml
OutputSuccess
Important Notes

Make sure your schema file is correct before generating code.

Generated code can be customized by changing the config file plugins.

Run code generation again after schema changes to keep code up to date.

Summary

Code generation saves time by creating code from your database schema automatically.

Use a config file to tell the tool what to generate and from which schema.

Run the generator whenever your schema changes to keep code synced.