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/custom-native-directive/custom-native-directive.gql
directive @upper on FIELD_DEFINITION
type NameWithUpper {
name: String! @upper
}
type Query {
testUpperDirective(name: String!): NameWithUpper
}
Implementing Directive Logic
Define the directive as a schema transformer function and register it with $directive on the module. Like other builder methods, $directive is chained before $schema:
src/modules/custom-native-directive/index.ts
import { getDirective, MapperKind, mapSchema } from "@graphql-tools/utils";
import { defaultFieldResolver, type GraphQLSchema } from "graphql";
import { CustomNativeDirectiveModule } from "./typedef.ts";
const { Query, NameWithUpper } = CustomNativeDirectiveModule;
const queryResolver = Query.$fields({
testUpperDirective: Query.testUpperDirective.resolve(({ args }) => {
return {
name: args.name,
};
}),
});
function upperDirective(schema: GraphQLSchema) {
return mapSchema(schema, {
[MapperKind.OBJECT_FIELD]: (fieldConfig) => {
const upperDirective = getDirective(schema, fieldConfig, "upper")?.[0];
if (!upperDirective) {
return fieldConfig;
}
const { resolve = defaultFieldResolver } = fieldConfig;
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;
},
});
}
export default CustomNativeDirectiveModule
.$directive(upperDirective)
.$schema({
Query: queryResolver,
NameWithUpper: NameWithUpper.$fields({
name: NameWithUpper.name.key("name"),
}),
});
This example creates an @upper directive that converts string fields to uppercase. The directive transformer is registered via $directive and chained into $schema, following the same builder pattern as the rest of Baeta.
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.