Strongly typed resolvers
-
pnpm add -D @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-resolvers @graphql-codegen/introspectionNote that
@graphql-codegen/*are our plugins. We utilize them to generate types automatically:@graphql-codegen/typescript-resolvers: creates aResolverstype that you can use to add a type to your resolver map, ensuring your resolvers return values match the field types specified by your schema.
-
pnpx graphql-code-generator init- Configuration file to tell GraphQL Code Generator where and how to generate types.
- After running this command I did some modifications to it to get it working.
- Import the generated type into different files if you’ve split your resolvers into multiple modules, or if it is all in one file use
import type { Resolvers } from './__generated__/resolvers-types';.
Strongly typed context
You can type your context as well to foster a better dev exp.
-
Export its interface from your code:
// main.ts // ... export interface Context { ip: string; db: PrismaClient; } // ... -
And now in your
codegen.yml:# ... config: contextType: 'apps/server-statistics/src/main#Context' useIndexSignature: true # ...