【发布时间】:2020-05-10 14:52:45
【问题描述】:
我不知道如何命名这个问题,但这是我不确定的。
我有一个 React 前端,它正在对我们的 GraphQl 中间层进行 GraphQl 查询,该中间层通过调用我们的旧 REST api 来聚合数据。
例如,在 React 中,我可以调用 getCustomer 查询:
query getCustomer($id: Int!) {
getCustomer(id: $id) {
name
email
}
}
这将访问 getCustomer 解析器,然后解析器向我们的 REST customers/{id} 端点发出请求以返回我们的数据。
async function getCustomer(_, { id }, ctx) {
const customer = await ctx.models.customer.getCustomer(id);
return customer;
}
如果我要打印客户列表,则此请求很好。但是我的问题是如何根据我正在查询的数据在解析器中发出条件 API 请求?
假设每个客户可以有多个地址,并且这些地址位于不同的端点上。我很想在我的前端获得这样的地址:
query getCustomer($id: Int!) {
getCustomer(id: $id) {
name
email
address {
city
}
}
}
我的解析器如何根据我的types 和schemas 处理这个问题?基本上是这样的:
async function getCustomer(_, { id }, ctx) {
const customer = await ctx.models.customer.getCustomer(id);
[If the query includes the address field]
const addresses = await ctx.models.customer.getAddressesByCustomer(id);
customer.addresses = addresses;
[/If]
return customer;
}
最终,目标是让getCustomer 解析器能够根据查询中发送的字段跨多个端点返回所有客户数据,但不会发出那些额外的 API 请求,如果未请求字段。
【问题讨论】:
-
你用的是什么graphql库?
-
我们正在运行一个内部客户端来处理 GraphQl 请求 - 所以不使用 Relay 或 Apollo。
-
你有一个
info对象作为ctx后面的第四个参数吗? -
我们没有。但我注意到文档中提到了
info。这可能是我进一步研究的事情吗?