【发布时间】:2019-11-13 01:20:17
【问题描述】:
问题
看看这个 GraphQL 查询,
query {
asset {
name
interfaces {
created
ip_addresses {
value
network {
name
}
}
}
}
}
我如何只为 ip_addresses 上的 network 字段定义解析器?
我的第一个想法
阅读docs 给出单个嵌套查询的示例,例如
const resolverMap = {
Query: {
author(obj, args, context, info) {
return find(authors, { id: args.id });
},
},
Author: {
posts(author) {
return filter(posts, { authorId: author.id });
},
},
};
所以我想 - 为什么不将此模式应用于嵌套属性?
const resolverMap = {
Query: {
asset,
},
Asset: {
interfaces: {
ip_addresses: {
network: () => console.log('network resolver called'),
},
},
},
};
但这不起作用,当我运行查询时 - 我没有看到控制台日志。
进一步测试
我想确保如果解析器位于查询返回类型的根级别,则始终会调用它。
我的假设:
Asset: {
properties: () => console.log('properties - will be called'), // This will get called
interfaces: {
created: () => console.log('created - wont be called'),
ip_addresses: {
network_id: () => console.log('network - wont be called'),
},
},
},
果然我的控制台显示了
properties - will be called
令人困惑的部分
但不知何故,apollo 仍在为 created 和 ip_addresses 使用默认解析器,因为我可以在 Playground 中看到返回的数据。
解决方法
我可以按如下方式实现“单体”解析器:
Asset: {
interfaces,
},
接口解析器在哪里做这样的事情:
export const interfaces = ({ interfaces }) =>
interfaces.map(interfaceObj => ({ ...interfaceObj, ip_addresses: ip_addresses(interfaceObj) }));
export const ip_addresses = ({ ip_addresses }) =>
ip_addresses.map(ipAddressObj => ({
...ipAddressObj,
network: network(null, { id: ipAddressObj.network_id }),
}));
但我觉得这应该由默认解析器处理,因为这些自定义解析器实际上并没有做任何事情,而是将数据传递给另一个解析器。
【问题讨论】:
标签: apollo apollo-server