feat: express decorators for rest apis and websocket (#6818)

* feat: express decorators for rest apis and websocket

* fix: added package dependency

* fix: refactor decorators
This commit is contained in:
M. Palanikannan 2025-03-26 20:24:05 +05:30 committed by GitHub
parent ae6e5a48fa
commit 993713925a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 690 additions and 7 deletions

View file

@ -0,0 +1,61 @@
import { RequestHandler, Router } from "express";
import "reflect-metadata";
type HttpMethod =
| "get"
| "post"
| "put"
| "delete"
| "patch"
| "options"
| "head"
| "ws";
interface ControllerInstance {
[key: string]: unknown;
}
interface ControllerConstructor {
new (...args: any[]): ControllerInstance;
prototype: ControllerInstance;
}
export function registerControllers(
router: Router,
Controller: ControllerConstructor,
): void {
const instance = new Controller();
const baseRoute = Reflect.getMetadata("baseRoute", Controller) as string;
Object.getOwnPropertyNames(Controller.prototype).forEach((methodName) => {
if (methodName === "constructor") return; // Skip the constructor
const method = Reflect.getMetadata(
"method",
instance,
methodName,
) as HttpMethod;
const route = Reflect.getMetadata("route", instance, methodName) as string;
const middlewares =
(Reflect.getMetadata(
"middlewares",
instance,
methodName,
) as RequestHandler[]) || [];
if (method && route) {
const handler = instance[methodName] as unknown;
if (typeof handler === "function") {
if (method !== "ws") {
(
router[method] as (
path: string,
...handlers: RequestHandler[]
) => void
)(`${baseRoute}${route}`, ...middlewares, handler.bind(instance));
}
}
}
});
}