This post covers two types of directive, one which can be used at runtime, sometimes referred to as a Query-Type Directive and the other used as part of the SDL (Schema Definition Language) sometimes referred to as a Schema-Type Directive.

Custom directives are not covered in this post.

Here’s a section from graphql.org

A directive can be attached to a field or fragment inclusion, and can affect execution of the query in any way the server desires. The core GraphQL specification includes exactly two directives, which must be supported by any spec-compliant GraphQL server implementation:

@include(if: Boolean) Only include this field in the result if the argument is true.

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

Directives can be useful to get out of situations where you otherwise would need to do string manipulation to add and remove fields in your query. Server implementations may also add experimental features by defining completely new directives.

As stated, there are exactly two directives for spec-compliant GraphQL server implementations but you can also write custom directives.

Let’s start with the 2 mentioned above.

query getUsers ($skipId: Boolean!) {
users {
id @skip(if: $skipId)
firstName
lastName
email
roles @include(if: $includeRoles) {
name
}
}
}
// Query Variables
{
"skipId": true,
"includeRoles": true
}

As you can see I’ve used both in the example above. It’s simple, it’s skipping the id and including the roles .

If you were like me and looking at this, thinking…

what is the point in these directives?? why not write a query without the id and just include roles, it will give you the same result.

Think about it like this…

You write one query with the directives and it saves you having to write another query which is slightly different.

Use vairables and this way you can keep your code a little bit DRYer.

So, you get a new requirement to add new fields to your GraphQL API but customers might still be using the old fields, you can just remove it, it’ll break things!

Mark it as @deprecated, with a reason message to explain the change. You can implement this using the example below.

type User {
id: ID!
fullName: String @deprecated(reason: "Separated into 2 props.")
firstName: String
lastName: String
email: String!
roles: [Role]
}

The graphiql docs will be updated to show the deprecated fields with the reason message. No need to version the API.

There it is, they’re easy to use and handy to know. The query-type directive gives the GraphQL consumers flexibility when creating queries for their apps, whereas the schema-type directive give the developer the ability to let the consumer know of up coming changes.

Happy coding!

Lead Developer. Angular. Node. GraphQL. JavaScript enthusiast.