@swastikbhattacharyya/next-actions
Version:
A type-safe utility for defining server actions and backend data access layers.
78 lines • 2.35 kB
JavaScript
// src/action.ts
var Action = class {
context;
validators;
actionFn;
constructor() {
this.context = {};
this.validators = [];
}
/**
* Defines the Zod schema for the action's input.
*
* This schema is not enforced automatically. To perform validation, use a
* validator like `zodValidator`.
*
* @param schema - The Zod schema to associate with the action.
* @returns Same instance with updated schema context.
*/
setInputSchema(schema) {
Object.assign(this.context, {
inputSchema: schema
});
return this;
}
/**
* Adds a validator function to the action pipeline.
*
* The validator can extend the context and contribute to the combined error
* map.
*
* @param validator - A validation function to run before the action executes.
* @returns Same instance with extended context and error map.
*/
addValidator(validator) {
this.validators.push(validator);
return this;
}
/**
* Sets the final action function to execute after all validators succeed.
*
* The action function receives the input params and the accumulated context.
*
* @param actionFn - The function to execute as the main action.
* @returns A bound execute function that runs the complete pipeline.
*/
setActionFn(actionFn) {
this.actionFn = actionFn;
return this.execute.bind(this);
}
/**
* Executes the validation pipeline followed by the main action function.
*
* If any validator fails, returns a structured error result.
* Otherwise, runs the action function and returns its result.
*
* @param params - The input parameters to validate and pass to the action.
* @returns A promise resolving to an {@link ActionResult}.
*/
async execute(params) {
if (!this.actionFn) throw new Error("Action function is undefined");
for (const validator of this.validators) {
const result = await validator({ params, context: this.context });
if (!result.ok)
return {
success: false,
message: "Validation failed",
errorCode: result.errorCode,
errorPayload: result.payload
};
else Object.assign(this.context, result.context);
}
return this.actionFn({ params, context: this.context });
}
};
export {
Action
};
//# sourceMappingURL=action.js.map