Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass obtained field to another (nested) query in GraphQL

Tags:

graphql

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 ?

like image 585
Adam Wolski Avatar asked Nov 11 '17 16:11

Adam Wolski


People also ask

How do you pass two arguments in GraphQL query?

Multiple arguments can be used together in the same query. For example, you can use the where argument to filter the results and then use the order_by argument to sort them.

How do you query a nested object in GraphQL?

When setting up a field whose value is a custom type, we have to define a function that tells GraphQL how to get that custom type. In our case, we want to tell GraphQL how to get the posts if we have the author. We do that by defining a new root property inside resolvers.

What is __ Typename in GraphQL?

The __typename field returns the object type's name as a String (e.g., Book or Author ). GraphQL clients use an object's __typename for many purposes, such as to determine which type was returned by a field that can return multiple types (i.e., a union or interface).


1 Answers

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) 
like image 74
Daniel Rearden Avatar answered Sep 23 '22 21:09

Daniel Rearden