I've been tackling a project that involves using annotations to implement routing for an express API app. However, I'm running into a problem where the route list is coming up empty at runtime.
Despite trying various resources, I haven't been able to figure out how to resolve this issue.
// RouteService File
export const routes: {
path: string,
router: string[]
}[] = [];
export function GetDynamicRoutes(): string[] {
let router: string[] = [];
routes.forEach(route => {
router = router.concat(route.router);
})
return router;
}
// Decorators File
import { routes } from "../service/route.service";
import { AbstractController } from "../controller/abstract.controller";
export function Route(path: string) {
return function (constructor: Function) {
routes.push({
path,
router: constructor.prototype.router
});
}
}
export function RouteRequest(path?: string) {
return function (target: Object, key: string | symbol,
descriptor: PropertyDescriptor) {
if (target.isPrototypeOf(AbstractController)) {
const router = (target as AbstractController).router;
const endpoint = path ? path : key.toString();
router.push(endpoint);
}
}
}
// AbstractController file
export class AbstractController {
public router: string[];
constructor() {
this.router = [];
}
}
// TestController File
import { Route, RouteRequest } from "../decorator/route.decorator";
import { AbstractController } from "./abstract.controller";
@Route('test')
export class TestController extends AbstractController {
@RouteRequest()
helloWorld() {
console.log('inside-hello-world');
}
}
// Main File
import { GetDynamicRoutes } from "./service/route.service";
function main() {
const routes = GetDynamicRoutes();
console.log(routes);
}
main();
This code snippet provides guidance on how to implement dynamic routing in separate files with appropriate imports and decorators.
https://codesandbox.io/s/youthful-goldwasser-t8byo?fontsize=14&hidenavigation=1&theme=dark