Using Prisma with GraphQL Codegen

Warren Day
tomorrowapp
Published in
3 min readMay 28, 2020

Both Codegen and Prisma automatically generate types. But a little extra config is required to make them play together nicely.

Generating types with Prisma

Prisma client has full TypeScript support out of the box. The client will be generated within your node_modules folder. Follow the official guide for specific details: https://www.prisma.io/docs/understand-prisma/introduction

But basically you generate a client by running

prisma generate

Generating types with Codegen

GraphQL Codegen can be used for many different scenarios. But in the context of a GraphQL API, you will want typings for your resolvers. These are generated automatically based on your GraphQL schema.

Take the following config (codegen.yml)

schema: src/**/*.graphql
generates:
./src/types/resolvers-types.ts:
plugins:
- add: |-
- typescript
- typescript-resolvers

This will tell codegen to search for any files with the extension .graphql and add all typings to a single file ./src/types/resolvers-types.ts

Generate the file by running

graphql-codegen 

You can then utilize the typings on your resolvers by importing the file and adding the type.

Making the two play nicely

Now, this may be all you need. But you’ll notice a small issue when working with relationships. Take for example the following resolver.

Here you can see we have defined a Query type to return a Booking with an id and receiptNumber. But Prisma actually has the value set as receiptCode.

Now here lies the problem; by default, TypeScript will throw an error because it automatically assumes that the type of Booking is equal to that defined in the GraphQl schema, meaning booking.receiptCode does not exist. We need to map to the type generated by Prisma.

To ensure Codegen maps the Prisma type you will need to update your codegen.yml.

schema: src/api/**/*.graphql
generates:
./src/types/resolvers-types.ts:
plugins:
- add: |-
- typescript
- typescript-resolvers
config:
mapperTypeSuffix: Model
mappers:
Booking: ‘@prisma/client/index.d#Booking’

Here we have added some extra config which tells Codegen to reference the Booking type that was generated by Prisma Client.

Bonus: To ensure there are no naming conflicts in the generated output add a mapperTypeSuffix. This means if your Prisma type and GraphQL type are both named Booking you won't run into any issues with naming collisions.

Put the two together as a single command and your good to go.

prisma generate && graphql-codegen

This solution also works great for other ORMs such as Sequalize. Any questions please ask in the comments :)

--

--