Supercharge Your Schemas with

Custom Directives

Ryan Chenkie

  • Angular/Node Consultant

@ryanchenkie

  • Google Developer Expert

  • angularcasts.io

What is a

Schema Directive?

"Directives provide a way to describe alternate runtime execution and type validation behavior in a GraphQL document."

– GraphQL Spec 2.12 (June 2018 release)

Built-In Directives

"GraphQL implementations should provide the @skip and @include directives."

– GraphQL Spec 3.13 (June 2018 release)

(queries)

Built-In Directives

"GraphQL implementations that support the type system definition language must provide the @deprecated directive if representing deprecated portions of the schema."

– GraphQL Spec 3.13 (June 2018 release)

(schemas)

What do schema directives look like?

foo: String

@myDirective

(myArg: "Bar")

What kinds of problems can we solve with schema directives?

Anything that requires a change to behavior at runtime

  • Internationalization
  • Authentication and access control
  • String formatting
  • Caching
  • Async work such as REST API calls

Implementing custom schema directives used to suck

Now it's easy with Apollo

Let's go for a visit

SchemaDirectiveVisitor
visitFieldDefinition
visitObject
visitSchema
visitScalar
visitArgumentDefinition
visitInterface
visitUnion
visitEnum
visitEnumValue
visitInputObject
visitInputFieldDefinition

What is the directive named?

What arguments does it take?

Where does it work?

Put the directive on any fields desired

Target field definitions

Get the argument passed in

Resolve the field with "something different"

Register the schema directive

Directives can be async 

Using context for authorization

Schema directives aren't the only option

Middleware is another option

npm install graphql-middleware

Slides

bit.ly/schema-directives

Thank You!

@ryanchenkie

Supercharge Your Schemas with Custom Directives

By Ryan Chenkie

Supercharge Your Schemas with Custom Directives

GraphQL's schema language is beautiful. It allows us to author data models concisely and communicate with teammates clearly. Using Apollo, we can also write directives to supercharge our schemas with custom behavior. Let's talk about how to write custom directives and the benefits they offer.

  • 6,251