Docblock tags
Directive definitions
On this page
To define a GraphQL directive, put a @gqlDirective docblock before a function declaration.
import type { Int } from "gratos";
/**
* @gqlDirective on FIELD_DEFINITION
*/
function cost(args: { credits: Int }) {
// ...
}directive @cost(credits: Int!) on FIELD_DEFINITIONThe 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:
- an optional name for the directive (without one, the function's name is used);
- an optional
repeatablekeyword, if the directive is repeatable; - the
onkeyword, followed by a list of directive locations separated by|.
import type { Int } from "gratos";
/**
* @gqlDirective cost repeatable on FIELD_DEFINITION | OBJECT
*/
function applyCost(args: { credits: Int }) {
// ...
}directive @cost(credits: Int!) repeatable on FIELD_DEFINITION | OBJECTArguments
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.
type SomeType = any;
/**
* @gqlDirective on FIELD_DEFINITION
*/
function myDirective(args: { someArg: string }, someNonGqlArg: SomeType) {}directive @myDirective(someArg: String!) on FIELD_DEFINITIONIn this style, define default values with the = operator, destructuring. You must destructure in the parameter list, not in the function body:
/**
* @gqlDirective on FIELD_DEFINITION
*/
function myDirective({ greeting = "Hello" }: { greeting: string }) {}directive @myDirective(greeting: String! = "Hello") on FIELD_DEFINITIONArguments can be marked @deprecated with the @deprecated JSDoc tag:
/**
* @gqlDirective on FIELD_DEFINITION
*/
function myDirective(args: {
/** @deprecated Unused! */
someArg?: string | null;
}) {
// ...
}directive @myDirective(someArg: String @deprecated(reason: "Unused!")) on FIELD_DEFINITION