roger
roger

Reputation: 1263

Typing for graphql resolver function

Looked at examples on how to write type for currying functions, but I still can’t connect the two.

This is the function I have for my resolver

export default {
  Query: { 
    Name: getResolver(‘name’, ‘special’)
  }
}

function getResolver(n: string, type: string) {
   return (parent, args, ctx) => { ... }
}

I try to do this but it does not work.

type GetResolver = <t, t1, t2>() => (parent: t...) => ... 

and

type NameResolver = (t, t1, t2)=> ...
type GetResolver = (...) => NameResolver

I know those types are wrong, but I am not sure what is missing here.

How do we write type for graphql resolver functions?

Upvotes: 0

Views: 280

Answers (1)

hackape
hackape

Reputation: 19947

Work in progress. Waiting for response from OP.

Check below, I still don't get the whole picture, need more input. Nonetheless I put together this piece of code base on your comment.

interface NameParent {}
interface NameArgs {}

const resolvers = {
  name: {
    special: function (parent: NameParent, args: NameArgs, ctx: any) {
      return 'string'
    },
    junk: function (parent: NameParent, args: NameArgs, ctx: any) {
      return 1
    }
  }
}

type ResolverType = keyof typeof resolvers

function getResolver<T extends ResolverType, K extends 'special' | 'junk'>(type: T, key: K) {
  return resolvers[type][key]
}

const specialNameResolver = getResolver('name', 'special')
// const specialNameResolver: (parent: NameParent, args: NameArgs, ctx: any) => string

const junkNameResolver = getResolver('name', 'junk')
// const junkNameResolver: (parent: NameParent, args: NameArgs, ctx: any) => number

Upvotes: 2

Related Questions