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
36 lines (35 loc) • 1.21 kB
TypeScript
import { z } from "zod";
export type Middleware<Input extends z.ZodTypeAny, Context extends Record<string, any>> = (props: {
input: z.infer<Input>;
context: Context;
}) => Promise<typeof props>;
export type HandlerProps<Input extends z.ZodTypeAny, Context extends Record<string, any>> = {
schema?: Input;
context: Context;
middleware: Middleware<Input, Context>[];
};
export declare class Container<Context extends Record<string, any>> {
private context;
constructor(context: Context);
createHandler<I extends z.ZodTypeAny>(schema?: I): Handler<I, Context>;
}
export declare class Handler<Input extends z.ZodTypeAny, Context extends Record<string, any>> {
private schema?;
private context;
private middlewares;
constructor(props: HandlerProps<Input, Context>);
private processMiddlewares;
use(middleware: Middleware<Input, Context>): this;
execute<Output>(fn: (props: {
input: z.infer<Input>;
context: Context;
}) => Promise<Output>): (input?: z.infer<Input>) => Promise<{
ok: boolean;
data: Awaited<Output>;
error: null;
} | {
ok: boolean;
data: null;
error: unknown;
}>;
}