1

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?

1 Answer 1

3

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']

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.