Explore essential concepts and real-world applications of GraphQL directives with this engaging quiz. Assess your understanding of how to modify queries, handle conditional logic, and leverage built-in and custom directives within GraphQL schemas.
Which GraphQL directive would you use to include a field only if a certain variable is true, such as in the example: { user { email @include(if: $showEmail) } }?
Explanation: @include is the correct directive for conditionally including a field based on a provided Boolean variable. @skip is used to exclude fields when a condition matches, not to include them. @map and @onIf are not valid GraphQL directives; they do not exist in the official GraphQL specification. Only @include allows for this positive conditional behavior.
If you want to omit a GraphQL field from the response when a certain variable is true, which built-in directive should be used?
Explanation: @skip is the proper directive to avoid including a field in the response when its condition is true. @iftrue and @filter are not official GraphQL directives and would not be recognized by the language. @ignore also does not exist in the specification. Only @skip provides this exclusion feature.
What is required when defining a custom directive in a GraphQL schema, such as directive @uppercase on FIELD_DEFINITION?
Explanation: When declaring a custom directive, you must specify its valid locations, like FIELD_DEFINITION, to define where it can be applied. Assigning a resolver function is not part of the schema definition phase; logic is typically handled at runtime. There is no naming convention requiring lowercase directive names, and directives are not restricted to types; they are usable on fields, arguments, etc. Omitting the location would make the directive invalid.
In a GraphQL query, how are multiple directives processed when attached to a single field, such as @include and @deprecated?
Explanation: GraphQL processes all attached directives independently, so their effects stack based on their purposes. Only considering the first directive or requiring mutual exclusivity are misconceptions not supported by GraphQL specifications. It is entirely valid to combine multiple directives on the same field as long as they make logical sense together.
Which statement best describes the use of variables with directive arguments in GraphQL queries?
Explanation: GraphQL allows variables to be passed into directive arguments, letting clients control behaviors like field inclusion at runtime. Limiting directive arguments to literals is incorrect, as is hardcoding values only at query declaration. Variable support is not restricted to schema types—directives using variables are standard on query fields.