【问题标题】:How do I use the apollo-server default resolver with a function?如何将 apollo-server 默认解析器与函数一起使用?
【发布时间】:2019-07-02 07:51:05
【问题描述】:

在 Graphql-tools 文档的默认解析器部分中,它声明

  1. 从 obj 中返回具有相关字段名称的属性,或者
  2. 使用相关字段名称调用 obj 上的函数并将查询参数传递给该函数

https://www.apollographql.com/docs/graphql-tools/resolvers.html#Default-resolver

类型定义:

type AggregateMessage {
  count: Int!
}

鉴于此查询解析器:

Query: {
    async messagesConnection(root: any, args: any, context: any, info: any) {
      const messages: IMessageDocument[] = await messageController.messages();

      const edges: MessageEdge[] = [];
      for (const node of messages) {
        edges.push({
          node: node,
          cursor: node.id
        });
      }
      // return messages;
      return {
        pageInfo: {
            hasNextPage: false,
            hasPreviousPage: false
        },
        edges: edges,
        aggregate: {
          count: () => {
            // Resolve count only
            return 123;
          }
        }
      };
   }
}

因此,如果我像这样手动定义解析器,它就可以工作。

AggregateMessage: {
    count(parent: any, args: any, context: any, info: any) {
      return parent.count();
      // Default resolver normally returns parent.count
      // I want it to return parent.count() by default
    }
}

但如果我删除定义并依赖默认解析功能,它就不起作用了。

如果我删除手动解析器并依赖默认解析器行为来调用属性名称上的函数,我希望它按照文档中的第 2 点调用函数 parent.count()。

  1. 使用相关字段名称调用 obj 上的函数并传递 将参数查询到该函数中

但是它给出了一个类型错误,因为“count”被定义为一个 Int 类型,但它实际上是一个函数。如何正确执行此操作,以便调用计数函数并在解析时返回值,而无需自己定义解析器?

Int cannot represent non-integer value: [function count]

【问题讨论】:

  • @Egor 你的意思是链接别的东西吗?
  • 是的,很抱歉)它的实际链接graphql.org/learn/queries/#mutations
  • 上面的代码没有理由不工作。我可以像普通 js 一样在本地运行它,所以我怀疑这是一个打字稿问题。包含您看到的错误(包括跟踪)会很有帮助,否则任何人都很难帮助您。
  • 查看您对 AggregateMessage 的定义也可能会有所帮助。我怀疑您将 count 定义为 number 而不是 number | () => number
  • Typescript 没有抛出错误。当我查询 apollo-server 时出现错误(代码编译并运行)。我正在使用graphql SDL,所以不确定如何定义它可以作为函数返回的类型。我特别尝试依赖 apollo-server 默认解析器功能。因此,如果我如图所示定义 AggregateMessage 解析器,那么它可以工作,但是如果我删除 AggregateMessage 解析器,如果 count 是一个函数,它就不起作用,但如果 count 返回一个数字,它就可以工作。

标签: graphql apollo-server


【解决方案1】:

这个问题原来是由 graphql-tools 中的 mergeSchemas 引起的。

将解析器传递给 mergeSchemas(而不是传递给 apollo-server 或 makeExecutableSchema)时,函数的默认解析器功能无法正常工作。

https://github.com/apollographql/graphql-tools/issues/1061

我不确定这是否是预期的功能,但将解析器移动到 makeExecutableSchema 调用解决了这个问题。

【讨论】:

    猜你喜欢
    • 2019-01-15
    • 2019-01-12
    • 1970-01-01
    • 2017-12-22
    • 2018-09-29
    • 2018-09-05
    • 2019-12-12
    • 2021-07-29
    • 2018-04-19
    相关资源
    最近更新 更多