Pass obtained field to another query in GraphQL

2020-03-10 06:11发布

问题:

Imagine the following query:

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 ?

回答1:

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.

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.

Edit: 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)


回答2:

I agree with @DanielRearden. You should make type-resolvers so you can go infinitely deep into the graph. I made a simple server example here that shows deep relationships. Because all the noun-fields are references, it goes infinitely deep for any query.

With that server, you can run a query like this, for example:

{
  hero {
    name
    friends {
      name
      friends {
        name
        friends {
          name
          friends: {
            name
          }
        }
      }
    }
  }
}

So, in your example, structure it like this:

query {
  user {
    id
    otherStuff {
      id
    }
  }
}


标签: graphql