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...

问题:

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.


回答1:

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
  }
}
  • 发表于 2019-02-19 13:34
  • 阅读 ( 207 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除