TypeScript Resolvers

This plugin generates TypeScript signature for resolve functions of your GraphQL API. You can use this plugin a to generate simple resolvers signature based on your GraphQL types, or you can change it's behavior be providing custom model types (mappers).

You can find a blog post explaining the usage of this plugin here: https://the-guild.dev/blog/better-type-safety-for-resolvers-with-graphql-codegen

Installation

Using yarn
$ yarn add -D @graphql-codegen/typescript-resolvers

API Reference

useIndexSignature

type: boolean default: false

Adds an index signature to any generates resolver.

Usage Examples

generates:
path/to/file.ts:
plugins:
- typescript
- typescript-resolvers
config:
useIndexSignature: true

noSchemaStitching

type: boolean default: false

Disables Schema Stitching support.

Note: The default behavior will be reversed in the next major release. Support for Schema Stitching will be disabled by default.

Usage Examples

generates:
path/to/file.ts:
plugins:
- typescript
- typescript-resolvers
config:
noSchemaStitching: true

wrapFieldDefinitions

type: boolean default: true

Set to true in order to wrap field definitions with FieldWrapper. This is useful to allow return types such as Promises and functions. Needed for compatibility with federation: true when

customResolveInfo

type: string default: graphql#GraphQLResolveInfo

You can provide your custom GraphQLResolveInfo instead of the default one from graphql-js

Usage Examples

generates:
path/to/file.ts:
plugins:
- typescript
- typescript-resolvers
config:
customResolveInfo: ./my-types#MyResolveInfo

customResolverFn

type: string default: (parent: TParent, args: TArgs, context: TContext, info: GraphQLResolveInfo) => Promise<TResult> | TResult

You can provide your custom ResolveFn instead the default. It has to be a type that uses the generics <TResult, TParent, TContext, TArgs>

Usage Examples

Custom Signature
generates:
path/to/file.ts:
plugins:
- typescript
- typescript-resolvers
config:
customResolverFn: ./my-types#MyResolveFn
With Graphile
generates:
path/to/file.ts:
plugins:
- add: "import { GraphileHelpers } from 'graphile-utils/node8plus/fieldHelpers';"
- typescript
- typescript-resolvers
config:
customResolverFn: |
(
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo & { graphile: GraphileHelpers<TParent> }
) => Promise<TResult> | TResult;

addUnderscoreToArgsType

type: boolean

Adds _ to generated Args types in order to avoid duplicate identifiers.

Usage Examples

config:
addUnderscoreToArgsType: true

contextType

type: string

Use this configuration to set a custom type for your context, and it will effect all the resolvers, without the need to override it using generics each time. If you wish to use an external type and import it from another file, you can use add plugin and add the required import statement, or you can use a module#type syntax.

Usage Examples

Custom Context Type
plugins
config:
contextType: MyContext
Custom Context Type
plugins
config:
contextType: ./my-types#MyContext

fieldContextTypes

type: Array_1

Use this to set a custom type for a specific field context. It will only affect the targeted resolvers. You can either use Field.Path#ContextTypeName or Field.Path#ExternalFileName#ContextTypeName

Usage Examples

Custom Field Context Types
plugins
config:
fieldContextTypes:
- MyType.foo#CustomContextType
- MyType.bar#./my-file#ContextTypeOne

rootValueType

type: string

Use this configuration to set a custom type for the rootValue, and it will effect resolvers of all root types (Query, Mutation and Subscription), without the need to override it using generics each time. If you wish to use an external type and import it from another file, you can use add plugin and add the required import statement, or you can use both module#type or module#namespace#type syntax.

Usage Examples

Custom RootValue Type
plugins
config:
rootValueType: MyRootValue
Custom RootValue Type
plugins
config:
rootValueType: ./my-types#MyRootValue

mapperTypeSuffix

type: string

Adds a suffix to the imported names to prevent name clashes.

Usage Examples

plugins
config:
mapperTypeSuffix: Model

mappers

type: object

Replaces a GraphQL type usage with a custom type, allowing you to return custom object from your resolvers. You can use both module#type and module#namespace#type syntax.

Usage Examples

Custom Context Type
plugins
config:
mappers:
User: ./my-models#UserDbObject
Book: ./my-models#Collections#Book

defaultMapper

type: string

Allow you to set the default mapper when it's not being override by mappers or generics. You can specify a type name, or specify a string in module#type or module#namespace#type format. The default value of mappers it the TypeScript type generated by typescript package.

Usage Examples

Replace with any
plugins
config:
defaultMapper: any
Custom Base Object
plugins
config:
defaultMapper: ./my-file#BaseObject
Wrap default types with Partial

You can also specify a custom wrapper for the original type, without overriding the original generated types, use "{T}" to specify the identifier. (for flow, use $Shape<{T}>)

plugins
config:
defaultMapper: Partial<{T}>
Allow deep partial with utility-types
plugins
plugins:
- "typescript"
- "typescript-resolvers"
- add: "import { DeepPartial } from 'utility-types';"
config:
defaultMapper: DeepPartial<{T}>

avoidOptionals

type: boolean default: false

This will cause the generator to avoid using optionals (?), so all field resolvers must be implemented in order to avoid compilation errors.

Usage Examples

generates:
path/to/file.ts:
plugins:
- typescript
- typescript-resolvers
config:
avoidOptionals: true

showUnusedMappers

type: boolean default: true

Warns about unused mappers.

Usage Examples

generates:
path/to/file.ts:
plugins:
- typescript
- typescript-resolvers
config:
showUnusedMappers: true

enumValues

type: EnumValuesMap

Overrides the default value of enum values declared in your GraphQL schema, supported in this plugin because of the need for integration with typescript package. See documentation under typescript plugin for more information and examples.

resolverTypeWrapperSignature

type: string default: Promise<T> | T

Allow you to override resolverTypeWrapper definition.

federation

type: boolean default: false

Supports Apollo Federation

enumPrefix

type: boolean default: true

Allow you to disable prefixing for generated enums, works in combination with typesPrefix.

Usage Examples

Disable enum prefixes
config:
typesPrefix: I
enumPrefix: false

optionalResolveType

type: boolean default: false

Sets the __resolveType field as optional field.

immutableTypes

type: boolean default: false

Generates immutable types by adding readonly to properties and uses ReadonlyArray.

scalars

type: ScalarsMap

Extends or overrides the built-in scalars and custom GraphQL scalars to a custom type.

Usage Examples

config:
scalars:
DateTime: Date
JSON: "{ [key: string]: any }"

namingConvention

type: NamingConvention default: pascal-case#pascalCase

Allow you to override the naming convention of the output. You can either override all namings, or specify an object with specific custom naming convention per output. The format of the converter must be a valid module#method. Allowed values for specific output are: typeNames, enumValues. You can also use "keep" to keep all GraphQL names as-is. Additionally you can set transformUnderscore to true if you want to override the default behavior, which is to preserves underscores.

Usage Examples

Override All Names
config:
namingConvention: lower-case#lowerCase
Upper-case enum values
config:
namingConvention:
typeNames: pascal-case#pascalCase
enumValues: upper-case#upperCase
Keep names as is
config:
namingConvention: keep
Remove Underscores
config:
namingConvention:
typeNames: pascal-case#pascalCase
transformUnderscore: true

typesPrefix

type: string default: ``

Prefixes all the generated types.

Usage Examples

config:
typesPrefix: I

skipTypename

type: boolean default: false

Does not add __typename to the generated types, unless it was specified in the selection set.

Usage Examples

config:
skipTypename: true

nonOptionalTypename

type: boolean default: false

Automatically adds __typename field to the generated types, even when they are not specified in the selection set, and makes it non-optional

Usage Examples

config:
nonOptionalTypename: true

Usage Example

Quick Start with typescript-resolvers

Run graphql-codegen as usual, with this new plugin:

schema: schema.json
generates:
./src/resolvers-types.ts:
plugins:
- typescript
- typescript-resolvers

Import the types from the generated file and use in the resolver:

import { Resolvers } from './resolvers-types';
export const resolvers: Resolvers = {
Query: {
myQuery: (root, args, context) => {},
}
};

This will make the resolver fully typed and compatible with typescript compiler, including the handler's arguments and return value.

Generated resolvers can be passed directly into graphql-tools makeExecutableSchema function.

Integration with Apollo-Server

If you are using Apollo Server with TypeScript, note that you need to set useIndexSignature: true in your config, in order to add a compatible index signature (more info).

If you wish to have an easy start, and have the ability to use resolvers chaining without models types, you can also add to your config defaultMapper: Partial<{T}>. This will allow you to return partial typse in your resolvers.