Input Directives
While GraphQL doesn't natively support modifying query arguments and inputs through directives, Baeta provides a utility called Input Directives that enables this functionality.
Target Types
Input directives can target different types of inputs:
scalar: For primitive values like numbers, strings, etc.list: For array valuesobject: For complex object inputs
Defining Input Directives
First, define your input directive in the schema:
src/modules/directives/input-directives.gql
directive @increment(by: Int!) on INPUT_FIELD_DEFINITION | ARGUMENT_DEFINITION
type Query {
testIncrementDirective(value: Int! @increment(by: 1)): Int!
}
Implementing Input Directives
Use the createInputDirective utility from @baeta/core to create the directive, then register it with $directive on the module:
src/modules/custom-input-directive/index.ts
import { createInputDirective } from "@baeta/core";
import type { Context } from "../../types/context.ts";
import { CustomInputDirectiveModule } from "./typedef.ts";
const { Query } = CustomInputDirectiveModule;
const incrementDirective = createInputDirective<{ by: number }, Context>({
name: "increment",
target: "scalar",
resolve: ({ directiveConfig, getValue, setValue }) => {
const value = getValue();
if (typeof value === "number") {
setValue(value + directiveConfig.by);
}
},
});
const queryResolver = Query.$fields({
testIncrementDirective: Query.testIncrementDirective.resolve(({ args }) => {
return args.value;
}),
});
export default CustomInputDirectiveModule
.$directive(incrementDirective)
.$schema({
Query: queryResolver,
});
How It Works
The input directive processes the input value before it reaches the resolver:
getValue()retrieves the original input value.- The directive logic modifies the value.
setValue()updates the input value.
Usage
When querying, the directive will modify the input before it reaches the resolver:
query {
testIncrementDirective(value: 5) {
# value will be incremented to 6 before reaching the resolver
}
}
This feature is particularly useful for input validation and data transformation.
For more examples and implementations, visit the Baeta directives examples.