Type Safety for GraphQL Data

When using a GraphQL client like urql, one of the issues you may run into is that your query and mutation responses are not typed.

For example, let’s say we have a cart query:

import { gql } from 'urql'

export const GetCart = gql`
  query GetCart {
    cart {
      contents {
        nodes {
          key
          product {
            node {
              id
              productId: databaseId
              name
              shortDescription
            }
          }
          quantity
          total
          subtotal
          subtotalTax
        }
      }
      total
    }
  }
`

When we use this query, it would be nice to see autocompletion in our editor, as well as errors if we try to access a property that doesn’t exist.

Unfortunately, we just get a type of any ☹️

What we really want is this:

How do we make that happen?

GraphQL Code Generator

The graphql-codegen library has our back.

Installing this library and running their script will generate all the types we need inside our project. It visits our graphql API and then creates a graphql.ts file inside our project with the types we need. In our case above, we now have a type for our GetCartQuery:

That’s what allows us to have autocompletion and errors in our editor.

To add graphql-codegen to your project requires a bit of setup, but it’s worth it to have type safety for our API responses. You have to install the library, create a configuration file, run the script to generate your types, then change your queries to use the new graphql() function that has all the new types.

To use this in your project, see the docs for urql here, or visit their website for instructions on other frameworks.


Posted

in

by

Tags: