【问题标题】:Passing the query param from top level to filed level将查询参数从顶层传递到字段级别
【发布时间】:2019-10-05 08:56:07
【问题描述】:
我有一个类似如下的 graphql 查询:
userInfo (id: userId) {
name
email
address {
street
country
}
}
因此name 和email 将由名为details 的休息端点解析,但是address 字段需要由另一个名为address 的休息端点解析。 address 休息端点还需要 userId 传入 userInfo (因为我的休息服务期望该字段)。我不确定,在这种情况下如何设计我的解析器?
同样的问题,一个字段一旦解析可以发送数据到另一个字段吗?这在 grapqhql 中可能吗?
【问题讨论】:
标签:
graphql
apollo
apollo-server
【解决方案1】:
我会添加(对@daniel 的回答)您可以在查询中明确传递此 id(w/o address 解析器更改)。
userInfo (id: userId) {
name
email
address (userID: userId) {
street
country
}
}
为了使其(address 解析器)通用,我们可以使用两个参数源:
async (parent, args, context, info) => {
// `parent` (user) can contain `id` property
return getAddress(args.userID ? args.userID : parent.id)
}
因为你应该有可能只查询地址(对于给定的userId),因为它可以使用 rest api。
【解决方案2】:
在 GraphQL 中,每个字段都解析到一个特定的值。在 GraphQL.js 中,该值可以是解析器返回的任何值,或者,如果解析器返回一个 Promise,则该 Promise 解析为的任何值。该值作为第一个参数传递给每个子字段的解析器。
实际上,这意味着即使您的类型具有特定字段并且您返回的对象应该与这些字段匹配,它也可以包含任意数量的附加属性。
例如,您的userInfo 解析器可能如下所示:
async (parent, args, context, info) => {
const { name, email } = await getDetails(args.id)
return {
name
email
id: args.id,
}
}
即使您没有id 字段,我们仍然可以将其包含在我们返回的对象中。这样,我们可以将一些额外的信息(例如我们的参数)传递给任何子字段的解析器。然后,在您的 address 解析器中:
async (parent, args, context, info) => {
// `parent` contains `name`, `email` and `id` properties
return getAddress(parent.id)
}