30
loading...
This website collects cookies to deliver better user experience
This article was published on 2020-05-17 by Dotan Simha @ The Guild Blog
typescript-resolvers
plugin.yarn add @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-resolvers
codegen.yml
file with the following, make sure to point to your schema location:schema: YOUR_SCHEMA_LOCATION_HERE
generates:
./resolvers-types.ts:
plugins:
- typescript
- typescript-resolvers
GraphQL Code Generator uses graphql-tools
so you can point to your schema files, or /graphql
endpoint.
yarn graphql-codegen
(or, create a script for it if you wish). This should create a new file called resolvers-types.ts
in your codebase.Resolvers
identifier from your generated file, and use it to type your resolvers object, for example:typescript-resolvers
is using the base type generated by typescript
, that means, that your schema types and resolvers needs to match and have the same signature and structure.mappers
configuration.User
object from example - in most cases, the representation of User
in your database (or any other downstream API) is different than the way your represent User
in your API. Sometimes it's because of security considerations, and sometimes because fields are internal and used only by you, and not by the consumers.type
, interface
or class
), or created automatically from your downstream APIs, database or any other data-source that you use in your app.mappers
.mappers
configuration, we need first to setup a real type safety, and have models types for our actual objects.mappers
and add a mapping between a GraphQL type to a TypeScript type (and the file it's located in):typescript-resolvers
also supports replacing the context
type of your resolvers implementation. All you have to do, is to add this following to your codegen configuration:schema: schema.graphql
generates:
./resolvers-types.ts:
config:
contextType: models#MyContextType
mappers:
User: ./models#UserModel
Profile: ./models#UserProfile
plugins:
- typescript
- typescript-resolvers
any
with MyContextType
, and you'll be able to access a fully-typed context
object in your resolvers.mappers
on every GraphQL type, interface or a union.args
) are also fully-typed, according to your schema definition.parent
value is also fully typed, based on your mappers
.User: models-lib#UserType
).DateType: Date
)User: ./models#User as MyCustomUserType
)defaultMapper
) and allow partial resolution, this will allow you to return partial objects in every resolver (more info):config:
useIndexSignature: true
defaultMapper: Partial<{T}>