Utilizing The Power of Typescript and GraphQL Codegen

Fajar Septiawan
ZebraX
Published in
5 min readNov 26, 2021

In this article, we’ll try to tell our journey on using GraphQL and GraphQL Code Generator with Typescript on the Frontend Development team.

The Idea of Using GraphQL Codegen

Starting from the first time, we were still using Javascript in our project, then we moved to use Typescript since it supports static typing and is easier to read and understand. Also, it’s useful because this way you can detect potential bugs before they happen in runtime. We want to take advantage of static typing to convert GraphQL schemas into Typescript types and to allow our GraphQL Operations (query/ mutation/ subscription, and fragment) to select specific types from them using GraphQL Code Generator.

Basic Fetching Data

For example, let’s say we want to integrate an API that retrieves User List and use it on our React project using Typescript and Apollo Client by implementing types in each schema manually.

Let’s assume that we have a simple GraphQL query:

// GET_USER_QUERY
query users {
users {
data {
id
name
username
email
}
}
}

Add the types of our query

// Types
export
interface UserData {
id: string
name: string
username: string
email: string
}
export interface Users {
data: UserData[]
}
export interface RootResponse {
users: Users
}

And then we need to call the query in our client-side application:

// React component
import
{ useQuery } from '@apollo/client'
import GET_USER_QUERY from '~/queries/users'
const User = () => {
const { data } = useQuery<RootResponse>(GET_USER_QUERY)
// `data` is fully typed based on your GraphQL query
return
(
*/ Render */
)
}

Everything works perfectly and all seems good and ready to go. Seems pretty simple right? Then how about this query:

query usersWithPostsComments($options: PageQueryOptions){
users(options: $options){
data {
id
username
email
name
posts {
data {
title
body
comments {
data {
name
email
body
}
}
}
}
}
}
}
Or deeper than the queries above.

We might find some issues when dealing with queries that deep:

  1. Just a single typo on the query or type definition can cause a bug that will take a lot of time to track and fix.
  2. We might already imagine the scenario where the developer gets too frustrated keeping track of what attributes and types are in the API, especially when dealing with multi-level data objects in a single query.
  3. As you can see, it might take a while to write all those manual types and queries, not to mention we need to edit them manually too should the query get updated (attribute change, addition, or removal).

At this point, it would be great if there is something we can use to check everything for us and do all the tedious work of writing the types every time we need to integrate. So, what exactly can we do to prevent such complexity from eating up our precious work hours?

Graphql Code Generator To The Rescue.

GraphQL Code Generator is a CLI tool that can generate Typescript types out of a GraphQL schema and operations (query/ mutation/ subscription, and fragment). GraphQL Code Generator can be applied to the popular frontend framework, in this case, we use React, Typescript, and Apollo as GraphQL Client.

Some benefits we find when we are implementing GraphQL Code Generator:

  1. GraphQL Code Generator can generate more than just TypeScript types. It can automate some of your GraphQL development workflows, generate common practices for data fetching, and add type-safety to code you usually need to write manually.
  2. We can generate ready-to-use React hooks for your GraphQL operations.
  3. We can focus on the business logic that must be applied to our project.
  4. Backend and Frontend Sync, when you make a change to the backend, the Codegen can spot any breaking changes instantly.

You can start GraphQL Codegen Getting Started and configuration for typescript. GraphQL Codegen provides several useful plugins and presets that you can implement as needed. We’ll try to generate Schemas, and Operations using React Hooks.

Generate: React & Apollo hooks, and Types

// gqlconfig.js
module.exports = {
overwrite: true,
generates: {
'src/gqlcodegen/types.ts': {
schema: process.env.YOUR_GRAPHQL_HOST,
plugins: ['typescript'],
config: {
// ...Plugin Config
},
},
'src/gqlcodegen/operations/': {
schema: process.env.YOUR_GRAPHQL_HOST,
preset: 'near-operation-file',
documents: 'src/gqlcodegen/operations/*.graphql',
presetConfig: {
extension: '.ts',
baseTypesPath: '../types.ts',
folder: '../hooks',
},
plugins: ['typescript-operations', 'typescript-react-apollo'],
config: {
// ...Plugin Config
},
},
},
}

At this point, GraphQL Codegen will generate our GraphQL Operations using preset ‘near-operation-file’ and plugins ‘typescript-operations’, ‘typescript-react-apollo’ from reading our query with format ‘.graphql’ inside the same destination folder.

Now we can move our queries above into the new file GraphQL Operations.

// ~/gqlcodegen/operations/user.graphqlquery usersWithPostsComments($options: PageQueryOptions){
users(options: $options){
data {
id
username
email
name
posts {
data {
title
body
comments {
data {
name
email
body
}
}
}
}
}
}
}

Finally, we just need to use a magic word (or magic command, if you prefer) that can be called in the command prompt or you can register inside package.json

graphql-codegen — config ./path/to/gqlconfig.js

The Answers

√ Parse configuration
√ Generate outputs

You will get a bunch of types that you can import, which is pretty handy. You also get hooks! useusersWithPostCommentQuery() and useUsersWithPostCommentstLazyQuery() which lets you pass the arguments and outcomes of your typed data.

import { useUsersWithPostsCommentsQuery } from '~/gqlcodegen/hooks/user'const User = () => { 
const { data } = useUsersWithPostsCommentsQuery()

return (
<div>
<ul>
{data?.users?.data?.map((user) => (
<li>
{/* Call user into component */}
</li>
))}
</ul>
</div>
)
}
export default User

To get familiar, you can try generating the code for another custom query you can make from the API. This way, you will have a firm understanding of how GraphQL Codegen works, and hopefully, how it would help you work with your project!

Conclusion

In our Frontend Development team want to make our project and the code as simple and readable as possible. GraphQL Codegen can help speed up development time, and no more hassle to think about and create Types for our GraphQL Operations as GraphQL Codegen will take care of it all, so we can focus on developing business logic on every frontend project. Hopefully, you are now able to try utilizing GraphQL Codegen in your project, or at least have a ground knowledge to research further into this topic.

Please let me know in the comments if you have any questions or tips, and share if you think this article is interesting or will helpful for others.

--

--