GraphQL dynamic query building

GraqhQL provides directives for this very purpose.

Create a fragment to define common fields, use @include(if: Boolean) and @skip(if: Boolean) directives on that fragment to get dynamic fields. By dynamic fields we mean fields that are known at execution time.

According to spec, it is best to avoid manual string interpolation to construct dynamic queries.

Directives1 make it possible to include or skip a field based on a boolean expression passed as a query variable. A directive can be attached to a field or fragment inclusion, and can affect execution of the query in any way the server desires.

query Hero($episode: Episode, $withFriends: Boolean!) {
  hero(episode: $episode) {
    name
    friends @include(if: $withFriends) {
      name
    }
  }
}

And in variables:

{
  "episode": "JEDI",
  "withFriends": false
}

Of course you can send named queries as you did in your second example. Clients will batch the requests automatically.

Leave a Comment