【问题标题】:In Typescript how to properly declare a Mercurius resolver?在 Typescript 中如何正确声明 Mercurius 解析器?
【发布时间】:2022-12-24 15:11:16
【问题描述】:

我有一个定义如下的自定义上下文,我将其传递给 Mercurius。

export interface Context {
  prisma: PrismaClient
}

const prisma = new PrismaClient()

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

我的 Mercurius 定义如下。

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

我很难定义接受上下文对象的 resolvers

根据 Mercurius 文档,调用解析器函数时第二个参数是在 Graphql 中传递给它的参数,第三个参数是上下文对象。但是,如果我定义了如下解析器,我会从 Typescript 中得到错误。

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

似乎 Mercurius 定义了预期的签名,其中上下文参数的类型为 MercurialContext。在我的例子中,我的上下文不需要 MercuriusContext 中的额外信息,所以我不扩展它。所以,我不得不如下声明我的解析器。

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
      }
    }
  };

Typescript 中有什么优雅的方法来处理这个问题吗?

【问题讨论】:

    标签: typescript graphql fastify mercurius


    【解决方案1】:
    import type { IResolvers } from 'mercurius'
    
    const resolvers: IResolvers = {
        Query: {
            findFirst: async (_:any, args:any, ctx:any) => {
            …
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-12
      • 2020-10-07
      • 2011-03-29
      • 2016-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多