To define a GraphQL directive, put a @gqlDirective docblock before a function declaration.

cost.ts
import type { Int } from "gratos";
/**
 * @gqlDirective on FIELD_DEFINITION
 */
function cost(args: { credits: Int }) {
  // ...
}

The directive is defined as a function, but unlike field resolvers, Gratos never calls it. A function whose type matches the directive's arguments still helps you write the code that reads your directive's arguments.

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

Locations

The text after the @gqlDirective tag is parsed much like a GraphQL directive definition:

  1. an optional name for the directive (without one, the function's name is used);
  2. an optional repeatable keyword, if the directive is repeatable;
  3. the on keyword, followed by a list of directive locations separated by |.
applyCost.ts
import type { Int } from "gratos";
/**
 * @gqlDirective cost repeatable on FIELD_DEFINITION | OBJECT
 */
function applyCost(args: { credits: Int }) {
  // ...
}

Arguments

The first argument of the directive function is an object holding the directive's GraphQL arguments, as in the object-map style of field resolvers.

Gratos ignores the function's other arguments. So the function can also be part of the directive's implementation.

myDirective.ts
type SomeType = any;
/**
 * @gqlDirective on FIELD_DEFINITION
 */
function myDirective(args: { someArg: string }, someNonGqlArg: SomeType) {}

In this style, define default values with the = operator, destructuring. You must destructure in the parameter list, not in the function body:

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

Arguments can be marked @deprecated with the @deprecated JSDoc tag:

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