Directives
Sometimes a screen needs a field only in certain situations: show the reviews only when a panel is expanded, hide prices for guests. You could keep two versions of the query, but GraphQL offers something cleaner: directives. A directive starts with @ and attaches extra behaviour to a field or fragment.
@include and @skip
Every GraphQL server supports two directives in queries:
| Directive | Meaning |
|---|---|
@include(if: Boolean!) |
include this field only if the argument is true |
@skip(if: Boolean!) |
skip this field if the argument is true |
They are almost always combined with a variable, so the same query text serves both cases:
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type Review { stars: Int }
type Recipe { name: String, minutes: Int, reviews: [Review] }
type Query { recipe: Recipe }
`);
const recipe = {
name: 'Shakshuka',
minutes: 30,
reviews() {
console.log(' (loading reviews)');
return [{ stars: 5 }, { stars: 4 }];
},
};
const query = `
query RecipePage($withReviews: Boolean!) {
recipe {
name
minutes
reviews @include(if: $withReviews) { stars }
}
}
`;
for (const withReviews of [false, true]) {
console.log('withReviews =', withReviews);
const result = await graphql({
schema, source: query, rootValue: { recipe }, variableValues: { withReviews },
});
console.log(JSON.stringify(result.data));
}withReviews = false
{"recipe":{"name":"Shakshuka","minutes":30}}
withReviews = true
(loading reviews)
{"recipe":{"name":"Shakshuka","minutes":30,"reviews":[{"stars":5},{"stars":4}]}}
When the condition is false the field is removed before execution: its resolver never runs and the key is absent from the response (not null).
Directives on fragments
Directives also work on fragment spreads and inline fragments, so a whole group of fields can be toggled at once:
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type Product { name: String, price: Float, stock: Int, supplier: String }
type Query { product: Product }
`);
const product = { name: 'Kettle', price: 29.9, stock: 14, supplier: 'Acme' };
const query = `
query ProductView($isGuest: Boolean!) {
product {
name
... @skip(if: $isGuest) {
price
stock
}
...Admin @include(if: false)
}
}
fragment Admin on Product { supplier }
`;
for (const isGuest of [true, false]) {
const result = await graphql({
schema, source: query, rootValue: { product }, variableValues: { isGuest },
});
console.log(`isGuest=${isGuest}`, JSON.stringify(result.data));
}isGuest=true {"product":{"name":"Kettle"}}
isGuest=false {"product":{"name":"Kettle","price":29.9,"stock":14}}
The inline fragment ... @skip(if: $isGuest) { … } has no type condition: it only exists to group fields under one directive.
Combining both
If a field has both @skip and @include, it is included only when @skip is false and @include is true. In practice, pick one per field; it reads more clearly.
Other directives you'll meet
Directives are also used in schemas, to annotate types and fields. The spec defines a few:
type Product {
name: String
sku: String @deprecated(reason: "Use `code` instead.")
code: String
}
scalar URL @specifiedBy(url: "https://url.spec.whatwg.org/")
input Contact @oneOf {
email: String
phone: String
}@deprecatedmarks a field or enum value as deprecated. It still works, but tools warn about it and introspection reports it (see the Introspection lesson).@specifiedBylinks a custom scalar to its specification.@oneOf(newer) requires exactly one field of an input object.
Servers and tools add their own, such as @key in Apollo Federation or @auth in some frameworks. Custom schema directives are just metadata: the server code decides what they do.
Validation of directives
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`type Query { a: Int, b: Int }`);
for (const source of ['{ a @include }', '{ a @cache(seconds: 5) }', '{ a @skip(if: true) @skip(if: false) }']) {
const result = await graphql({ schema, source, rootValue: { a: 1, b: 2 } });
console.log(result.errors[0].message);
}Directive "@include" argument "if" of type "Boolean!" is required, but it was not provided.
Unknown directive "@cache".
The directive "@skip" can only be used once at this location.
Test yourself
What does reviews @include(if: false) { stars } produce in the response?
"reviews": null"reviews": []- No
reviewskey at all - A validation error
Which directive marks a schema field as outdated but still usable?
@skip@deprecated@oneOf@specifiedBy
What is the type of the if argument of @skip?
StringBooleanBoolean!Int