首页 > 解决方案 > 如何将 apollo-server 默认解析器与函数一起使用?

问题描述

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

标签: graphqlapollo-server

解决方案


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

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

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

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


推荐阅读