GraphQL动态查询构建 [英] GraphQL dynamic query building

查看:176
本文介绍了GraphQL动态查询构建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个GraphQL服务器,它能够为指定来源提供时间序列数据(例如,传感器数据).获取传感器数据的示例查询可能是:

I have a GraphQL server which is able to serve timeseries data for a specified source (for example, sensor data). An example query to fetch the data for a sensor might be:

query fetchData {
    timeseriesData(sourceId: "source1") {
      data {
        time
        value
      }
    }
}

在我的前端,我希望允许用户选择1个或多个源,并为每个源显示一条带线的图表.似乎可以通过使用如下查询来实现:

In my frontend, I want to allow the user to select 1 or more sources and show a chart with a line for each one. It seems like this would be possible by using a query like this:

query fetchData {
    series1: timeseriesData(sourceId: "source1") {
      data {
        time
        value
      }
    }
    series2: timeseriesData(sourceId: "source2") {
      data {
        time
        value
      }
    }
}

大多数GraphQL教程似乎都专注于静态查询(例如,唯一发生变化的是变量,而不是请求的实际形状)-但就我而言,我需要查询本身是动态的(对我选择的每个ID都有一个timeseriesData请求).

Most GraphQL tutorials seem to focus on static queries (e.g. where the only thing that is changing is the variables, but not the actual shape of the request) - but in my case I need the query itself to be dynamic (one timeseriesData request for each of my selected ids).

我有以下限制条件:

  1. 修改服务器的架构不是一种选择(例如,我无法将ID数组传递给解析器)
  2. 我的查询是使用模板字符串指定的,例如gql` ...`
  3. 我不想以字符串形式手动建立查询,因为这看起来像是灾难的秘诀,并且意味着我会失去所有工具优势(例如,自动完成,语法突出显示,掉毛)

我正在使用的堆栈是:

  • Apollo客户程序(特别是Apollo角形)
  • 角度
  • TypeScript
  • graphql-tag(用于定义查询)

理想情况下,我想做的是通过某种方式将两个查询合并为一个,这样我就可以按照第一个示例定义它们,然后将它们合并到一个抽象层中,这样我就可以得到一个查询通过电线发送的第二个示例.

Ideally, what I want to do is have some way of merging two queries into one, so that I can define them as per the first example but then join them together in an abstraction layer so that I get a single query like the second example to be sent over the wire.

但是我不确定如何实现此目标,因为graphql-tag正在将查询解析为AST,并且我正在努力了解以这种方式操作查询是否可行.

However I'm not sure how to achieve this because graphql-tag is parsing the query into an AST and I'm struggling to understand whether it's feasable to manipulate the query in this way.

有什么技术可以生成这样的动态查询,而查询的形状不是预先知道的?

What techniques are there for generating a dynamic query like this, where the shape of the query is not known upfront?

推荐答案

您可以使用片段来定义公共字段,并在该片段上使用变量绑定的@include(if: Boolean)@skip(if: Boolean)指令来获取在执行时已知的动态字段

You can use fragment to define common fields, and variable bound @include(if: Boolean) and @skip(if: Boolean) directives on that fragment to get dynamic fields that are known at execution time.

这篇关于GraphQL动态查询构建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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