UNPKG

@noony-serverless/core

Version:

A Middy base framework compatible with Firebase and GCP Cloud Functions with TypeScript

72 lines 2.96 kB
import { Context, CustomRequest, CustomResponse, GenericRequest, GenericResponse } from './core'; /** * Interface representing a base structure for middleware with optional lifecycle methods. * * This interface is designed to provide hooks for execution during different * stages of a middleware's lifecycle. It allows for defining logic to be * executed before and after a process, as well as handling errors that * occur during the process. * * @template T - The type of the request or input context. Defaults to unknown. * @template U - The type of the response or output context. Defaults to unknown. */ export interface BaseMiddleware<T = unknown, U = unknown> { before?: (context: Context<T, U>) => Promise<void>; after?: (context: Context<T, U>) => Promise<void>; onError?: (error: Error, context: Context<T, U>) => Promise<void>; } /** * The Handler class is responsible for managing and executing middleware functions * and a main handler function in a sequential and controlled manner. * * This class provides a mechanism for registering middlewares that can * process a request/response flow either before the main handler (via `before`), * after the main handler (via `after`), or handle errors (via `onError`). * * interface MessagePayload { * action: string; * data: Record<string, unknown>; * } * * const handler = new Handler<MessagePayload>() * .use(errorHandler()) * .use(bodyParser()) * .handle(async (context) => { * const { req } = context; * // Handle the request * }); * @template T Type for the input request data. * @template U Type for the additional context or response data. */ export declare class Handler<T = unknown, U = unknown> { private baseMiddlewares; private handler; private reversedMiddlewares; private errorMiddlewares; private middlewaresPrecomputed; static use<T = unknown, U = unknown>(middleware: BaseMiddleware<T, U>): Handler<T, U>; use<NewT = T, NewU = U>(middleware: BaseMiddleware<NewT, NewU>): Handler<NewT, NewU>; handle(handler: (context: Context<T, U>) => Promise<void>): Handler<T, U>; /** * Performance optimization: Pre-compute middleware arrays to avoid runtime array operations */ private precomputeMiddlewareArrays; execute(req: CustomRequest<T>, res: CustomResponse): Promise<void>; /** * Execute before middlewares with optimized batching for independent middlewares */ private executeBeforeMiddlewares; /** * Execute after middlewares using pre-computed reversed array */ private executeAfterMiddlewares; /** * Execute error middlewares using pre-computed array */ private executeErrorMiddlewares; /** * Framework-agnostic execute method that works with GenericRequest/GenericResponse */ executeGeneric(req: GenericRequest<T>, res: GenericResponse): Promise<void>; } //# sourceMappingURL=handler.d.ts.map