When interacting with the Github GraphQL API in Typescript, it would be nice to
leverage the power of types to understand the structure of queries, mutations, variables, and responses. Luckily, with a
little glue code between graphql-codegen and Github’s published schema
@octokit/graphql-schema, we can add types to all of our interactions with
the API.

If you’re looking for the TLDR, the complete sample code is available
on Github.

Prerequisites

If you don’t already have a Typescript / GraphQL repository initialized, go ahead and create one.

npx graphql-codegen init
Welcome to GraphQL Code Generator!
Answer few questions and we will setup everything for you.

? What type of application are you building? (Press <space> to select, <a> to toggle all, <i> to invert
selection)
❯◯ Backend - API or server
◯ Application built with Angular
◯ Application built with React
◯ Application built with Stencil
◯ Application built with other framework or vanilla JS

We’ll point graphql-codegen at the schema published by
@octokit/graphql-schema that we installed earlier. For now, type
src/generated/github-schema-loader.js and press enter. We’ll create that file in a subsequent step.

I like to write distinct GraphQL files for improved IDE support. To support this workflow, we want to use
typescript-document-nodes. To do so, use
the down arrow key to select “TypeScript GraphQL document nodes (embedded GraphQL document)”, press space and then press
enter.

? Where to write the output: (src/generated/graphql.ts)

In this case, the default suggestion (src/generated/graphql.ts) is just fine. Press enter to continue.

<trimmed>exporttypeRepository=Node&ProjectOwner&RegistryPackageOwner&RegistryPackageSearch&Subscribable&Starrable&UniformResourceLocatable&RepositoryInfo&{__typename?:'Repository';/** A list of users that can be assigned to issues in this repository. */assignableUsers:UserConnection;/** A list of branch protection rules for this repository. */branchProtectionRules:BranchProtectionRuleConnection;/** Returns the code of conduct for this repository */codeOfConduct?:Maybe<CodeOfConduct>;/** A list of collaborators associated with the repository. */collaborators?:Maybe<RepositoryCollaboratorConnection>;/** A list of commit comments associated with the repository. */commitComments:CommitCommentConnection;/** Identifies the date and time when the object was created. */createdAt:Scalars['DateTime'];/** Identifies the primary key from the database. */databaseId?:Maybe<Scalars['Int']>;/** The Ref associated with the repository's default branch. */defaultBranchRef?:Maybe<Ref>;/** Whether or not branches are automatically deleted when merged in this repository. */deleteBranchOnMerge:Scalars['Boolean'];/** A list of deploy keys that are on this repository. */<trimmed>

Checkpoint

Writing Queries and Mutations

Now that we have types generated let’s do something with them! We’ll write some simple GraphQL
queries and mutations with added type safety. I like to keep my queries and
mutations in their own folders, so create a directory for each:

mkdir-p src/mutations src/queries

And reference those directories in your codegen.yml file:

documents:-src/queries/*.graphql-src/mutations/*.graphql

For the next steps, you’ll also need a Github Personal Access token with repo scope. If you don’t already have one,
create one in your settings. For help doing this, check out this
Github support page.

Install Apollo

For this demo, I’ll use Apollo as my GraphQL client. Install Apollo
and its dependencies:

By providing the <WhoAmIQuery> type, Typescript now understands the object that will be returned from the query. We
can also pass the query as WhoAmI, instead of writing our GraphQL statement in-line as a string.

When we run this code, we should see our username written out to the console. To run the code, you’ll need to provide
your Github token generated above as the GITHUB_TOKEN environment variable. In your terminal, run:

This code will add a star on the repository ID you pass (docs).
Note that we’re using a GraphQL variable called starrableId that will
be set at runtime. Since we’ve added a .graphql file, we need to run codegen again.

Note that we’ve added the starRepo method that calls our new mutation. By passing
<AddStarMutation, AddStarMutationVariables>, Typescript will now ensure that we’re passing all the required variables
to the mutation, and that they’re of the correct type. This is great because it will help catch bugs before we even call
the Github API.

For example, if I don’t pass the required starrableId variable, I get a handy warning in my editor.

Note that we’re now calling getBenLimmerDotComRepoId() instead of hard-coding the value. Typescript is also helping us
make sure we have a null check, in case the repository can’t be found. That information from Typescript reminded us to
add this block of code to ensure the repository could be found from the API call:

Checkpoint

Conclusion

As part of this tutorial, we created a project to interact with the
Github GraphQL API. By using
graphql-codegen, we were able to add Typescript types to make interacting with
the API easier and safer.