Skip to content

Instantly share code, notes, and snippets.

@captbaritone
Created February 9, 2025 22:25
Show Gist options
  • Save captbaritone/6f8369241989bf1afa518acced5287a7 to your computer and use it in GitHub Desktop.
Save captbaritone/6f8369241989bf1afa518acced5287a7 to your computer and use it in GitHub Desktop.

Defining Directives

You can define GraphQL directives by placing a @gqlDirective before a:

  • Function declaration
  • Arrow function declaration
/**
 * @gqlDirective 
 * @gqlOn FIELD_DEFINITION
 */
function cost(args: {credits: Int}) {
  // ...
}

Note: While the directive is defined as a function, unlike field resolvers, Grats will not actually invoke your function. ****However, having a function whose type matches the arguments of your directive can be useful for writing code which will accept the arguments of your directive.

To annotate part of your schema with a directive, see @gqlAnnotate.

Directive Locations

Each directive definition must specify one or more locations where it’s valid to use the directive. This is done by adding one or more @gqlOn docblock tags followed by the location name:

/**
 * @gqlDirective 
 * @gqlOn FIELD_DEFINITION
 * @gqlOn TYPE_DEFINITION
 */
function cost(args: {credits: Int}) {
  // ...
}

The set of directive location’s can be found in the GraphQL Spec

Arguments

The first argument of the directive function is an object containing the directive’s GraphQL arguments. This mirrors the Object-style map fields style supported by field resolvers.

All other arguments to the directive function are ignored by Grats. This allows the function to be used as part of the implementation of the directive’s behavior.

/**
 * @gqlDirective on FIELD_DEFINITION
 */
function myDirective(args: {someArg: string}, someNonGqlArg: SomeType) {}

Default values in this style can be defined by using the = operator with destructuring. Note that you must perform the destructuring in the argument list, not in the function body:

/**
 * @gqlDirective on FIELD_DEFINITION
 */
function myDirective({greeting = "Hello"}: {greeting: string}) {}

Like positional arguments, object-map arguments can be marked as @deprecated by using the @deprecated JSDoc tag:

/**
 * @gqlDirective on FIELD_DEFINITION
 */
function myDirective(args: {
	  /** @deprecated Unused! */
  someArg: string
}) {}

Repeatable Directives

To specify that a directive may be applied more than once at a given location, you can add the docblock tag @gqlRepeatable:

/**
 * @gqlDirective
 * @gqlOn FIELD_DEFINITION
 * @gqlRepeatable
 */
function myDirective() {
  // ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment