Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

GraphQL Basics - GraphQL Directives

Overview of GraphQL Directives

GraphQL directives are special annotations that can be used to alter the behavior of a query or schema. They are useful for controlling execution at runtime and can be applied to fields, fragments, or queries.

Key Points:

  • Directives allow dynamic behavior in your GraphQL queries.
  • Common directives include @include and @skip.
  • They enhance the flexibility of your GraphQL API.

Common GraphQL Directives

@include Directive

The @include directive conditionally includes fields in the query based on a boolean variable.


// Example: Using @include directive
query getUser($showEmail: Boolean!) {
  user(id: "1") {
    name
    email @include(if: $showEmail)
  }
}
          

@skip Directive

The @skip directive is the opposite of @include; it conditionally skips fields in the query.


// Example: Using @skip directive
query getUser($hideEmail: Boolean!) {
  user(id: "1") {
    name
    email @skip(if: $hideEmail)
  }
}
          

Creating Custom Directives

You can also define custom directives to implement specific logic in your GraphQL schema. This involves defining the directive in your schema and implementing its behavior in the resolver.


// Example: Defining a custom directive
directive @uppercase on FIELD_DEFINITION

// Example: Using a custom directive
type User {
  name: String @uppercase
}
          

Best Practices for Using Directives

Follow these best practices when using directives in GraphQL:

  • Limit Directive Usage: Use directives judiciously to avoid complex and unreadable queries.
  • Document Custom Directives: Clearly document any custom directives to ensure maintainability.
  • Test Directive Logic: Thoroughly test the logic implemented in directives to prevent runtime errors.

Summary

This guide provided an overview of GraphQL directives, including common directives like @include and @skip, as well as the process of creating custom directives. Proper use of directives can greatly enhance the flexibility and capability of your GraphQL API.