Creating Custom Directives
Create directives by extending theGraphQL::Directive class:
app/graphql/directives/awesome_directive.rb
Directive Locations
Directives must specify where they can be used withplaced_on:
Definition Locations
For schema definition::schema- On schema definitions:scalar- On scalar types:object- On object types:field_definition- On field definitions:argument_definition- On argument definitions:interface- On interface types:union- On union types:enum- On enum types:enum_value- On enum values:input_object- On input types:input_field_definition- On input field definitions
Execution Locations
For query execution::query- On query operations:mutation- On mutation operations:subscription- On subscription operations:field- On field selections:fragment_definition- On fragment definitions:fragment_spread- On fragment spreads:inline_fragment- On inline fragments
Using Directives
On Definitions
Add directives to schema elements:- Symbol Reference
- Class Reference
- Instance
app/graphql/objects/user.rb
On Execution
Use directives in GraphQL queries:Built-in Directives
@deprecated
Mark fields or enum values as deprecated: Locations::field_definition, :enum_value
Repeatable: false
Arguments:
reason: String- Explanation of why it’s deprecated
@include
Conditionally include fields: Locations::field, :fragment_spread, :inline_fragment
Repeatable: false
Arguments:
if: Boolean!- Include when true
if is true:
if is false:
@skip
Conditionally exclude fields: Locations::field, :fragment_spread, :inline_fragment
Repeatable: false
Arguments:
if: Boolean!- Skip when true
if is true:
if is false:
@specifiedBy
Document scalar specifications: Locations::scalar
Repeatable: false
Arguments:
url: String!- URL to specification document
app/graphql/scalars/date_time_scalar.rb
Directive Arguments
Define arguments for your directives:app/graphql/directives/rate_limit_directive.rb
Directive Events
Directives are event-driven. Listen to events:Event Filters
Filter when events trigger:Repeatability
By default, directives can only appear once per location:Directive Examples
Authentication Directive
app/graphql/directives/auth_directive.rb
Caching Directive
app/graphql/directives/cached_directive.rb
Transform Directive
app/graphql/directives/uppercase_directive.rb
Loading Directives
Load directive dependencies in your schema:app/graphql/app_schema.rb
Best Practices
- Use symbol references - Reference directives by symbol, not class
- Document purpose - Add descriptions with
desc - Specify locations - Only allow directives where they make sense
- Handle errors - Raise appropriate errors in event handlers
- Use event filters - Target specific types or phases
- Make repeatable - When multiple instances make sense
- Keep focused - One directive should do one thing
- Test thoroughly - Directives affect many parts of your schema