Guide: GraphQL Modules
GraphQL Code Generator's @graphql-codegen/graphql-modules-preset
plugin helps to
generate resolvers type for each module of a GraphQL Modules GraphQL API.
Given the following GraphQL API structure using GraphQL Modules:
- src/
- modules/
- user/
- resolvers.ts
- typedefs/
- user.graphql
- product/
- resolvers.ts
- typedefs/
- product.graphql
Just a few configuration steps are required to get the resolvers types generated:
Install
npm i -D @graphql-codegen/graphql-modules-preset @graphql-codegen/typescript-resolvers @graphql-codegen/typescript
Configure the plugin
Create or update your codegen.ts
file as follows:
import type { CodegenConfig } from '@graphql-codegen/cli'
const config: CodegenConfig = {
schema: './src/modules/**/typedefs/*.graphql',
generates: {
'./server/src/modules/': {
preset: 'graphql-modules',
presetConfig: {
baseTypesPath: '../generated-types/graphql.ts',
filename: 'generated-types/module-types.ts'
},
plugins: [
{
add: {
content: '/* eslint-disable */'
}
},
'typescript',
'typescript-resolvers'
]
}
}
}
export default config
Run the codegen and update your code
Assuming that, as recommended, your package.json
has the following script:
{
"scripts": {
"generate": "graphql-codegen"
}
}
Running the following generates the graphql/generated.tsx
file.
npm run generate
The User module resolvers would be:
import { UsersModule } from './generated-types/module-types'
export const resolvers: UsersModule.Resolvers = {
// Here, you can implement only the types and fields defined in your module!
}
A complete article, written by Arda Tanrikulu from The Guild, is available on our blog: Writing a GraphQL TypeScript project w/ GraphQL-Modules and GraphQL-Code-Generator.
For more advanced configuration (models or context typing), please refer to the plugin documentation.