将获得的字段传递给 GraphQL 中的另一个(嵌套)查询 [英] Pass obtained field to another (nested) query in GraphQL

查看:23
本文介绍了将获得的字段传递给 GraphQL 中的另一个(嵌套)查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象以下查询:

query {
  user {
    id
  }
  SomeOtherStuff(id: <--- I want to pass the id obtained from user) {
    id
  }
}

如何将从一个查询获得的参数传递给另一个查询?

How do you pass a parameter obtained from one query to another ?

推荐答案

在 GraphQL 中,请求的每个级别"的字段都是并行执行和解析的.在您的示例中,userSomeOtherStuff 都是相同类型的字段(根 Query 类型)——因此它们将在同时.这意味着每个查询本质上都不知道对方或对方解析了什么.

In GraphQL, fields at each "level" of the request are executed and resolved in parallel. In your example, user and SomeOtherStuff are both fields of the same type (the root Query type) -- so they will be resolved at the same time. That means each query essentially is not aware of the other or what the other resolved to.

您将不得不处理这种场景客户端.换句话说,先请求用户,解析 id 的响应,然后发出第二个请求.

You would have to handle this kind of scenario client side. In other words, request the user first, parse the response for the id and then make the second request.

在 Apollo 中,您将为此目的使用 compose:

In Apollo, you would utilize compose for this purpose:

const userQuery = gql`query User { user { id } }`;
const stuffQuery = gql`query SomeOtherStuff($id: ID) { someOtherStuff(id: $id){ stuff } }`;

export default compose(
  graphql(userQuery, { name: 'userData' })
  graphql(stuffQuery, { name: 'stuffData', options: ({userData:{id}={}}) => ({variables: {id}}) }),
)(YourComponent)

这篇关于将获得的字段传递给 GraphQL 中的另一个(嵌套)查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆