gpt4 book ai didi

reactjs - GraphQl 和条件解析器 API 请求

转载 作者:行者123 更新时间:2023-12-04 10:41:55 25 4
gpt4 key购买 nike

我不知道如何命名这个问题,但这是我不确定的。

我有一个 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 如何执行请求。仅当 1)“父”字段不为空且 2) 实际请求相关字段时,才会调用字段的解析器。这意味着我们可以明确地为地址字段提供解析器:

const resolvers = {
Customer: {
addresses: () => {
return ctx.models.customer.getAddressesByCustomer(id)
},
},
}

这样,解析器将被调用以进行类似的查询
{
query getCustomer($id: Int!) {
getCustomer(id: $id) {
name
address {
city
}
}
}
}

但不会被要求
{
query getCustomer($id: Int!) {
getCustomer(id: $id) {
name
}
}
}

在包装简单的 REST API 时,这种方法非常有效。但是,某些 REST API 允许您通过可选参数请求相关资源。同样,如果您要从数据库中提取数据,则可以将其他表连接到您的查询中。最终结果是在更少的往返中获得更多的数据。在这种情况下,您将在根级别(在 getCustomer 解析器内)执行所有获取操作。但是,您需要确定自定义实际请求的字段。为此,您可以 parse the resolve info object ,这是传递给每个解析器的第四个参数。一旦确定实际请求了哪些字段,就可以对 URL 或 SQL 查询进行适当的更改。

关于reactjs - GraphQl 和条件解析器 API 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59893717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com