my-handler
Version:
Simple Handler is a lightweight and flexible utility wrapper, heavily inspired by tRPC, designed for use in my personal projects. It provides an easy way to create and manage handlers with schema validation (powered by Zod) and middleware support for adva
60 lines • 1.71 kB
JavaScript
import { z } from "zod";
export class Container {
context;
constructor(context) {
this.context = context;
}
createHandler(schema) {
return new Handler({
schema: schema,
context: this.context,
middleware: [],
});
}
}
export class Handler {
schema;
context;
middlewares;
constructor(props) {
this.schema = props.schema;
this.context = props.context ?? {};
this.middlewares = props.middleware;
}
async processMiddlewares(input) {
let processedInput = input;
for (const middleware of this.middlewares) {
const result = await middleware({
input: processedInput,
context: this.context,
});
processedInput = result.input;
}
return processedInput;
}
use(middleware) {
this.middlewares.push(middleware);
return this;
}
execute(fn) {
return async (input) => {
let processedInput = {};
try {
if (this.schema) {
const validatedInput = await this.schema.parseAsync(input);
processedInput = await this.processMiddlewares(validatedInput);
}
const result = await fn({
input: processedInput,
context: this.context,
});
return { ok: true, data: result, error: null };
}
catch (error) {
console.error(error);
return { ok: false, data: null, error: error };
}
};
}
}
//# sourceMappingURL=mod.js.map