Supercharge Your Schemas with

Custom Directives

Ryan Chenkie

  • JavaScript Consultant

@ryanchenkie

  • Google Developer Expert

  • angularcasts.io

Consumer or Creator?

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

youtu.be/4_Bcw7BULC8

Now it's easy with Apollo

Let's visit the schema

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?

Target field definitions

Get the argument passed in

Resolve the field with "something different"

Register the schema directive

Put the directive on any fields desired

Directives can be async 

Using context for authorization

Schema directives aren't the only option

Middleware is another option

npm install graphql-middleware

There's an emerging preference for code-first schemas

bit.ly/schema-first

Problems with Schema First

  • Schemas and resolvers must be kept in sync
  • Modularizing schemas
  • Redundancy in schemas
  • Developer experience
  • Composing distributed schemas

Lots of tooling needed to get around these problems

Code-first server development can offer benefits

Slides

bit.ly/custom-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.

  • 1,398