Graphql 将多个查询合并(组合)为一个? [英] Graphql merge (combine) multiple queries into one?

查看:55
本文介绍了Graphql 将多个查询合并(组合)为一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 JavaScript 将多个 Graphql 查询合并为一个查询.
我正在寻找这样的东西:

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.

假设我有这样的查询:

输入查询1:

{
  post(id: 1234) {
    title
    description
  }
}

输入查询2:

{
  post(id: 1234) {
    tags
    author {
      name
    }
  }
}

然后我希望结果 query3 是:
结果查询3:

Then I would like the result query3 to be:
result query3:

{
  post(id: 1234) {
    title
    tags
    description
    author {
      name
    }
  }
}

这与 lodash _.merge() 为 JSON 对象所做的功能相同,但随后使用 Graphql 查询而不是 JSON 对象.

This would be the same functionality as lodash _.merge() does for JSON objects, but then with Graphql queries instead of JSON objects.

推荐答案

我的回答有点久久不能发表评论,所以我决定在这里写一个直接的回答.首先,我认为这两条评论都非常有帮助.有一个解决方案让两个查询共享一个 HTTP 请求,这可能已经是您正在寻找的优化.此外,合并查询并非易事.要做到这一点到现场级别需要付出很多努力.不仅片段会使这变得困难,您还必须考虑变量.据我所知,没有公开的解决方案可以做到这一点,所以你必须自己做.此外,我还没有听说过这样做的公司.我认为没有解决方案的事实表明这样做可能不值得.

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

这篇关于Graphql 将多个查询合并(组合)为一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆