I'm trying to combine multiple Graphql queries into one query using JavaScript.
I am looking for something like this:
let query3 = mergeQueries(query1, query2);
We won't know beforehand which queries will be combined.
Suppose I have queries like this:
input query1:
{
  post(id: 1234) {
    title
    description
  }
}
input query2:
{
  post(id: 1234) {
    tags
    author {
      name
    }
  }
}
Then I would like the result query3 to be:
result query3:
{
  post(id: 1234) {
    title
    tags
    description
    author {
      name
    }
  }
}
This would be the same functionality as lodash _.merge() does for JSON objects, but then with Graphql queries instead of JSON objects. 
Thanks to parameterized fragments you can take variables into account! Assuming post is a field of the root query type the combined query referring to the above example would be:
fragment PostHeader on RootQueryType {
  post(id: $id) {
    tags
    author {
      name
    }
  }
}
fragment PostMeta on RootQueryType {
  post(id: $id) {
    tags
    author {
      name
    }
  }
}
# ID being the id type
query($id: ID! = 1234) {
  ...PostHeader
  ...PostMeta
}
or rather in a real-world scenario you'd be passing in the id dynamically (e.g. in your post request), see: https://graphql.org/learn/queries/#variables
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With