Directives
Directives in Baeta allow you to modify the execution behavior of your GraphQL schema. They can be applied to various parts of your schema and provide a way to add metadata or transform data.
Defining a Directive
src/modules/directives/directives.gql
directive @upper on FIELD_DEFINITION
type NameWithUpper {
name: String! @upper
}
type Query {
testUpperDirective(name: String!): NameWithUpper
}
Implementing Directive Logic
To implement the directive's behavior, use the $directive
method:
src/modules/directives/directives.ts
import { MapperKind, getDirective, mapSchema } from "@graphql-tools/utils";
import { defaultFieldResolver } from "graphql";
import { getCustomNativeDirectiveModule } from "./typedef";
const { $directive, Query } = getCustomNativeDirectiveModule();
$directive((schema) => {
return mapSchema(schema, {
// Executes once for each object field in the schema
[MapperKind.OBJECT_FIELD]: (fieldConfig) => {
// Check whether this field has the specified directive
const upperDirective = getDirective(schema, fieldConfig, "upper")?.[0];
if (!upperDirective) {
return fieldConfig;
}
// Get this field's original resolver
const { resolve = defaultFieldResolver } = fieldConfig;
// Replace the original resolver with a function that *first* calls
// the original resolver, then converts its result to upper case
fieldConfig.resolve = async (source, args, context, info) => {
const result = await resolve(source, args, context, info);
if (typeof result === "string") {
return result.toUpperCase();
}
return result;
};
return fieldConfig;
},
});
});
// Implement the query resolver
Query.testUpperDirective(({ args }) => {
return {
name: args.name,
};
});
This example creates an @upper
directive that converts string fields to uppercase. The directive is applied during schema creation and modifies the field's resolver to transform its output.
Usage
When querying, the directive will automatically transform the result:
query {
testUpperDirective(name: "hello") {
name # Will return "HELLO"
}
}
For more information on directives, see the GraphQL documentation and the Baeta directives example.