Generate GraphQL types for Typescript with CodeGen

Thomas Gazzoni

3 min read

GraphQL is a awesome tool to get a frontend guy jump into the backend world, that's right, I am talking to you Backend guy, soon you gonna be replace by a bunch of frontend engenier, Just kidding :>)

So, seems all cool and nice, but if your use (and it should be) favorite language isTypescript, you have three choices:

  1. use any everywhere (very very bad).
  2. create a lot of interface rapresenting all the Model Types, Queries, Mutation etc, so basicaly waste a lot of time.
  3. use a awesome tool GraphQL code generator and come back to be happy again.

How it works#

Well is pretty simple, this tool will fetch the GraphQL schema types directlly from the graphql server endpoint.

A simple Example#

Dependencies#

To get started we need some dependencies.

yarn add @graphql-codegen/cli @graphql-codegen/typescript@graphql-codegen/typescript-operations -D

Config#

Since this GraphQL code generator is a external tool, we need a cofiguration file, this file is called codegen.yml and is placed in the root of your project:

overwrite: true
schema: http://localhost:4000
documents: src/graphql/queries.ts
generates:
  src/graphql/types.ts:
    plugins:
      - typescript
      - typescript-operations

The config values is pretty simple, it contains those part:

  • schema: is a GraphQL server endpoint
  • documents: just point to a Typescript file containing all our Query and Mutations
  • generates: will contain the istruction for our output, aka all types definitions: models, query, input, mutation, etc, with this config will create the src/graphql/types.ts file.

The plugins part is where the magic happens. Thanks to this plugin we will get generate different outputs.

For a typescript project we will simply use typescript and typescript-operations plugins.

For a full list of available plugins you can check out this link.

The "documents"#

The documents config value can point to a file or, with some wildcard, to a bunch of files.

The files could be some .graphql files containing our needed GraphQL queries but then we still need to import it in typescript to give it

The final command#

Once we have our config in the root of our project, we can execute:

npx graphql-codegen

or use it with the watch flag to keep an eye on the queries.ts file changes:

npx graphql-codegen --watch

Finally we can add some handy scripts in the package.json for our convenience:

"scripts": {
  "codegen:dev": "graphql-codegen --watch",
  "codegen:prod": "graphql-codegen",
}

That's it! Now you can enjoy your free time :)


Subscribe to the newsletter