GraphQL dynamic query building : <p>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:</p>

<pre><code>query fetchData {
    timeseriesData(sourceId: "source1") {
      data {
        time
        value
      }
    }
}
</code></pre>

<p>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:</p>

<pre><code>query fetchData {
    series1: timeseriesData(sourceId: "source1") {
      data {
        time
        value
      }
    }
    series2: timeseriesData(sourceId: "source2") {
      data {
        time
        value
      }
    }
}
</code></pre>

<p>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 <em>query itself</em> to be dynamic (one timeseriesData request for each of my selected ids).</p>

<p>I have the following constraints:</p>

<ol>
<li>Modifying the server's schema is not an option (so I can't pass an array of IDs to the resolver, for example)</li>
<li>My query is specified using a template string e.g. gql`...`</li>
<li>I don't want to have to manually build up the query as a string, because that seems like a recipe for disaster and would mean that I lose all tooling benefits (e.g. autocomplete, syntax highlighting, linting)</li>
</ol>

<p>The stack I'm using is:</p>

<ul>
<li>Apollo client (specifically apollo-angular)</li>
<li>Angular </li>
<li>TypeScript</li>
<li>graphql-tag (for defining queries)</li>
</ul>

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

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

<p><strong>What techniques are there for generating a dynamic query like this, where the <em>shape</em> of the query is not known upfront?</strong></p>
