Directives

Intermediate · 5 min

Use @include and @skip to shape queries, @deprecated to retire fields, and how custom directives are declared but not run by default.

Before thisVariables and operation namesFragmentsEnums

Jamie Barton · 5 min

Directives

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Jamie BartonReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A directive is an annotation starting with @ that changes how a field, fragment, or schema element is treated, such as title @include(if: $show).
  • The query-side built-ins are @include(if:) and @skip(if:), both of which take a Boolean and work on fields, fragment spreads, and inline fragments.
  • The schema-side built-ins are @deprecated(reason:) for fields, arguments, enum values and input fields, and @specifiedBy(url:) for scalars, plus @oneOf for input objects.
  • Directives are checked by the validator: an unknown directive or a missing required argument is rejected.
  • Custom directives must be declared in the schema, but graphql-js gives them no behaviour; your server or a library has to implement what they do.

Changing a query without changing its text

Variables let you change values. A directive lets you change the structure of a query depending on a value, and it lives on a field, a fragment, or something in the schema. A directive is an @name with optional arguments, attached to the thing it affects.

The problem it solves: a card shows an author’s biography only on the detail page. You could write two queries. Or you could keep one and switch the field on and off:

query Card($full: Boolean!, $short: Boolean!) {
  book(id: "10") {
    title
    year @include(if: $full)
    price @skip(if: $short)
  }
}

The text stays fixed and the variables decide. Run on graphql-js 17.1.0:

Variables Response book
{"full": true, "short": false} title, year, price
{"full": false, "short": true} title only

@include(if: X) keeps the field when X is true. @skip(if: X) drops it when X is true. They are mirror images, and having both exists for readability. Put them together and both must agree. With title @include(if: true) @skip(if: true) the field was dropped, and the response was {"book":{}}.

They also work on fragment spreads and inline fragments. This returned an empty book when $on was false, since the whole fragment was skipped:

query($on: Boolean!) { book(id: "10") { ...F @include(if: $on) } }
fragment F on Book { title }

An important detail: a skipped field is not resolved. I counted calls to a resolver on a field with @skip(if: true) and got zero. That is the point, because a client can avoid expensive work with a variable. It is also why @include is the way to make a query conditional in client libraries, rather than fetching everything and ignoring it.

The validator checks directives

Two failures, both tested:

{ book(id: "10") { title @skip } }
# Argument "@skip(if:)" of type "Boolean!" is required, but it was not provided.

{ book(id: "10") { title @cache(ttl: 5) } }
# Unknown directive "@cache".

A directive must be declared by the schema before use. @include and @skip are built in, and a server has to define anything else.

Schema directives you will use

The built-ins in schema SDL are for documentation and tooling:

  • @deprecated(reason: String) marks a field, argument, input field, or enum value as on its way out. It keeps working. I added oldIsbn: String @deprecated(reason: "Use isbn13.") to Book and querying oldIsbn still returned data (null in my sample). Introspection tells tools about it, and a client asking with includeDeprecated: true gets the reason (introspection). This is how you evolve a schema without versions: evolving a schema without versions.
  • @specifiedBy(url: String!) points a custom scalar at its specification, as in scalar types.
  • @oneOf on an input object requires exactly one field (input types).

Asking a schema which directives it knows returns, on 17.1.0: include, skip, deprecated, specifiedBy, oneOf. The first two apply to FIELD, FRAGMENT_SPREAD and INLINE_FRAGMENT; deprecated applies to field, argument, input field, enum value and directive definitions.

Custom directives

You can declare your own in SDL:

directive @auth(role: String!) on FIELD_DEFINITION

The declaration tells the validator the directive exists, where it may appear (the on ... part), and what arguments it takes. It does not make anything happen. graphql-js ignores unknown behaviour: the server or a library has to read the directive and act on it. Common uses are authorisation, caching hints, formatting, and federation. Federation’s @key is a custom directive. Implementation varies by library, and the authentication and authorization and federation lessons show real examples. I did not implement a custom directive for this lesson; treat the exact API for that as something to read in your server’s docs.

When not to use them

  • Directives that change the shape of the response multiply the number of distinct shapes one query can produce, which makes typed clients harder. @include is the accepted exception.
  • Do not use directives to carry business logic that belongs in a resolver. They are easy to miss when reading code.
  • Overuse of conditional fields can mean you have one screen pretending to be two. Two named queries are often clearer.

What the video covers

Jamie Barton’s “@include, @skip, and @deprecated GraphQL Directives” is about five and a half minutes, published September 2021. Its description says it covers including or skipping fields, using skip and include with inline and spread fragments, and where the deprecated directive goes in a schema. That matches this lesson’s built-ins. I could not read a transcript. The runner-up is Ben Awad’s 2019 video on the skip directive and dynamic queries; its description links an Apollo post on static queries, so it is client-minded.

Where this fits

The last query-side idea turns the schema on itself: a query that asks the server what it can do. Next: introspection.

Check yourself

  1. 01What does a field with both @include(if: true) and @skip(if: true) do?

    It is left out, because a field is only included when include is true and skip is false.

  2. 02Where can @skip be used?

    On fields, fragment spreads, and inline fragments in an operation, never in the schema definition.

  3. 03How do you mark a field as deprecated, and what happens to clients that still use it?

    Add @deprecated(reason: "...") in the schema; the field keeps working and tools flag it, so clients can migrate before it is removed.

  4. 04You write @cache(ttl: 5) on a field. What does the server say if it was never declared?

    It rejects the query with Unknown directive @cache, because directives must be declared in the schema before use.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark