Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Graphql merge (combine) multiple queries into one?

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.

like image 905
Hendrik Jan Avatar asked Feb 18 '19 09:02

Hendrik Jan


1 Answers

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

like image 163
Kevin K. Avatar answered Sep 20 '22 09:09

Kevin K.