Dynamic Query Using Directives

Learn about dynamic GraphQL queries that use directives.

GraphQL directive

In the last lesson, we learned how to utilize GraphQL variables to filter pizzas based on a keyword entered by the user. Imagine now that our application has grown in popularity. Each pizza now requires a summary and a more thorough description , which also needs additional fields of data. We need a method to dynamically modify the structure and layout of our queries.

GraphQL has a feature called directive that allows this. A directive can be appended to a field or fragment and can influence the query’s execution in any way the server chooses. The GraphQL standard contains two default directives that each GraphQL server implementation must support:

  • @include(if: Boolean): We include this field if the argument is true.

  • @skip(if: Boolean) : We skip this field if the argument is true.

How to make a dynamic query

You need to do three things:

  • Using the previous query as a reference, we need to find fields that are conditionally used. We’ll then decide to load the toppings fields if withToppings is True.

  • We need to define withToppings as the variable and Boolean as the type since the value can only be either true or false. Since it’s mandatory, we also need to remember the exclamation mark (!).

  • We need to add directives to the toppings fields and remember to pass $withToppings.

We’re now able to refactor the previous query, reproduced below:

  • @include(if: Boolean) Include this field only if the argument is true.
  • @skip(if: Boolean) Skip this field if the argument is true.

How to make a dynamic query

You need to do three things:

  • Using the previous query as a reference, find fields that are conditionally used. Now you will decide to load toppings fields if withToppings is True
  • Define withToppings as variablesGraphQL features a feature called a directive that allows for this. A directive can be appended to a field or fragment and can influence the query’s execution in any way the server chooses. The GraphQL standard contains two default directives that each GraphQL server implementation must support: and a Boolean as the type since the value can only be true or false, and since it’s mandatory, don’t forget the exclamation mark (!).
  • Add directives to the toppings fields, and don’t forget to pass $withToppings.

We’re now able to refactor the previous query, reproduced below:

Get hands-on with 1400+ tech skills courses.