Mike
Mike

Reputation: 179

GraphQL - How do I use the return value as a variable for the next query?

How do I take the return result from the first query and assign that result to a variable to use in the second query? I need the first value result before I can make the second call, but would like to make only 1 call to accomplish this. My query:

query {
    test1(sku: "12345"){                    
          price
    }
    test2(itemPrice: $price){ 
          isSuccessful
    }
}

Upvotes: 7

Views: 3037

Answers (1)

Vishwa Ratna
Vishwa Ratna

Reputation: 6390

Your Query:

query {
    test1(sku: "12345"){                    
          price
    }
    test2(itemPrice: $price){ 
          isSuccessful
    }
}

When a query is parsed, it’s converted to an AST, or a tree. In your case your query will look like below:

enter image description here

Now there are 3 phases involved with every graphQl query :

1.Parse — A query is parsed into an abstract syntax tree (or AST). ASTs are incredibly powerful and behind tools like ESLint, babel, etc.

2.Validate — The AST is validated against the schema. Checks for correct query syntax and if the fields exist.

3.Execute — The runtime walks through the AST, starting from the root of the tree, invokes resolvers, collects up results, and emits JSON.

The root Query type is the entry point to the tree and contains our two root fields, test1 and test2. The test1 and test2 resolvers are executed in parallel (which is typical among all runtimes). The tree is executed breadth-first, meaning user must be resolved before its children price and isSuccessful are executed.

So basically in a single query you cannot solve your problem as of now.

Upvotes: 5

Related Questions