Skip to main content

Directive Definitions

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

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

While the directive is defined as a function, unlike field resolvers, Grats will not 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.

Locations

The text after the @gqlDirective tag is parsed similarly to a a GraphQL directive definition:

  1. An optional name for the directive (the function name will be used if no name is provided)
  2. An optional repeatable keyword if the directive is repeatable
  3. The on keyword followed by a list of directive locations separated by |.
/**
* @gqlDirective cost repeatable on FIELD_DEFINITION | TYPE_DEFINITION
*/
function applyCost(args: { credits: Int }) {
// ...
}

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 }) {}

Arguments can be marked as @deprecated by using the @deprecated JSDoc tag:

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