In Typescript how to properly declare a Mercurius resolver?

435 views Asked by At

I have a custom context as defined below, which I am passing to Mercurius.

export interface Context {
  prisma: PrismaClient
}

const prisma = new PrismaClient()

export const context: Context = {
  prisma: prisma,
}

My Mercurius definition is as below.

app.register(mercurius, {
  schema,
  resolvers,
  graphiql: true,
  context: () => context /* This is the context object from above */,
})

I am having difficulty defining resolvers which accept the context object.

As per Mercurius documentation the resolver function is called with second param being the arguments passed to it in Graphql and the third param is the context object. However, I get error from Typescript if I defined a resolver like below.

const resolvers = {
    Query: {
      findFirst: async (_:any, args:any, ctx:Context) => {
          //...
      }
    }
  };

It seems Mercurius defines the expected signature where the context param is of type MercurialContext. In my case my context does not need the extra info in MercuriusContext and so I do not extend that. So, I am forced to declare my resolver as below.

const resolvers = {
    Query: {
      findFirst: async (_:any, args:any, ctx:any) => {
          //...Then in my code I am using 'ctx as Context' to force it into my object
      }
    }
  };

Is there any elegant way in Typescript to handle this?

1

There are 1 answers

0
Olivier Penhoat On
import type { IResolvers } from 'mercurius'

const resolvers: IResolvers = {
    Query: {
        findFirst: async (_:any, args:any, ctx:any) => {
        …
        }
    }
}