graphql - 如何将 apollo-server 默认解析器与函数一起使用?
问题描述
在 Graphql-tools 文档的默认解析器部分中,它指出
- 从 obj 返回具有相关字段名称的属性,或
- 使用相关字段名称调用 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()。
- 使用相关字段名称调用 obj 上的函数并将查询参数传递给该函数
但是它给出了类型错误,因为“count”被定义为 Int 类型,但它实际上是一个函数。如何正确执行此操作,以便调用计数函数并在解析时返回值,而不必自己定义解析器?
Int cannot represent non-integer value: [function count]
解决方案
这个问题原来是由 graphql-tools 中的 mergeSchemas 引起的。
将解析器传递给 mergeSchemas(而不是传递给 apollo-server 或 makeExecutableSchema)时,函数的默认解析器功能无法正常工作。
https://github.com/apollographql/graphql-tools/issues/1061
我不确定这是否是预期的功能,但将解析器移动到 makeExecutableSchema 调用解决了这个问题。
推荐阅读
- python - 关于 predict_prob() 函数的理论问题 - 概率的显示顺序
- terraform - Terraform HCL - 将列表转换为对象地图?
- r - 我可以将observeEvent() 与bsplus::bs_accordion 一起使用吗
- bash - 使用“nohup”时,打印功能在整个程序完成之前不会打印
- neo4j - 如何使用 ORDER BY 的查询参数?
- java - docker上的JSch端口转发
- google-cloud-platform - Google AI Platform 上基于 SpaCy 的自定义预测
- jpa - 当不需要修改持久对象时分离它们是否正常?
- reactjs - React APP ReferenceError:未定义要求
- python - 标签标记器不起作用,无法计算损失和准确性