javascriptgraphql

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.


Solution

  • My answer is getting a bit to long for a comment so I decided to write a direct answer here. First I think both comments are really helpful. There is a solution that let's two queries share an HTTP request which might already be the optimisation you are looking for. Furthermore merging queries is not trivial. It requires a lot of effort to do this down to a field level. Not only fragments can make this difficult, you also have to take variables into account. As far as I know there is no solution publicly available to do that so you would have to do it yourself. Also I have not heard of a company that does this. I think that the fact that there is no solution is an indicator that it might not be worth it to do it.

    I can only guess your problem, but another way to reduce the amount of queries sent by a frontend application is to make use of fragments. While your fragments cannot have variables a healthy component structure will still fit very well with fragments:

    fragment PostHeader on Post {
      title
      description
    }
    
    fragment PostMeta on Post {
      tags
      author {
        name
      }
    }
    
    query {
      post(id: 1234) {
        ...PostHeader
        ...PostMeta
      }
    }