David
David

Reputation: 924

Auto-generate graphql resolver signatures

I have the following GraphQL Schema:

type User {
  id: ID
  name: String
}

type Mutation {
  createUser(name: String): User
}

And I want to create the signature and the resolver in typescript

type createUser = (name: string) => User; // <- signature

const createUserResolver: createUser = (name) => {} as User; // <- resolver

But if I define the createUser signature by hand and then the schema changes, I will need to update the signature.

Is there any way to auto-generate the signature when the schema changes?

Upvotes: 1

Views: 416

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84687

You can use the typescript-resolvers plugin of GraphQL Code Generator.

Example config:

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

Run codegen and then you can import a Resolvers type to use with your resolver map:

import { Resolvers } from './resolvers-types';

export const resolvers: Resolvers = {
  Mutation: {
    createUser: (root, args, context) => {
      // args type will be inferred based on your type definitions
    },
  }
};

If you need to extract an individual signature, you can do this: Resolvers['Mutation']['createUser']

Upvotes: 3

Related Questions