UNPKG

tspace-spear

Version:

tspace-spear is a lightweight, high-performance API framework for Node.js that leverages the native HTTP server and supports uWebSockets.js (C++) for maximum speed and efficiency.

61 lines 1.78 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Middleware = void 0; /** * Attaches a middleware function to a controller method. * * The middleware will be executed **before the route handler**. * If the middleware calls `next(err)`, the error will be forwarded * to the framework's error handler. Otherwise, the original * controller method will be executed. * * This decorator also stores middleware metadata using `Reflect.defineMetadata` * so the framework can discover and execute it during the request lifecycle. * * @example * ```ts * class UserController { * * \@Middleware(authMiddleware) * async profile(ctx: T.Context) { * return { user: ctx.user }; * } * * } * ``` * * Example middleware: * * ```ts * const authMiddleware: T.ContextHandler = (ctx, next) => { * if (!ctx.user) { * return next(new Error("Unauthorized")); * } * next(); * }; * ``` * * @param {T.ContextHandler} middleware - Middleware function to execute before the route handler. * @returns {MethodDecorator} */ const Middleware = (middleware) => { return (target, key, descriptor) => { const originalMethod = descriptor.value; descriptor.value = function (ctx, next) { try { Reflect.defineMetadata("middlewares", descriptor, target); return middleware(ctx, (err) => { if (err != null) { return next(err); } return originalMethod.call(this, ctx, next); }); } catch (error) { return next(error); } }; }; }; exports.Middleware = Middleware; //# sourceMappingURL=middleware.js.map