nestjs-router
Version:
39 lines (38 loc) • 1.6 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
require("reflect-metadata");
const constants_1 = require("@nestjs/common/constants");
const nestedClassType = {
modules: constants_1.MODULE_PATH,
controllers: constants_1.PATH_METADATA
};
class NestRouter {
static nestController(path, routes) {
return NestRouter.flattenRoutes(path, routes, constants_1.metadata.CONTROLLERS);
}
static nestModule(path, routes) {
return NestRouter.flattenRoutes(path, routes, constants_1.metadata.MODULES);
}
static flattenRoutes(rootPath, routes, type) {
let flatRoutes = [];
Object.keys(routes).forEach((path) => {
const target = routes[path];
if (target instanceof Function) {
let NestedClass = NestRouter.buildPath(rootPath, target, type);
flatRoutes.push(NestedClass);
}
flatRoutes = flatRoutes.concat(NestRouter.flattenRoutes(`${rootPath}/${path}`, target, type));
});
return flatRoutes;
}
static buildPath(rootPath, target, metaType) {
const oldPath = Reflect.getMetadata(nestedClassType[metaType], target);
const newPath = oldPath ? `${rootPath}/${oldPath}` : rootPath;
class NestedClass extends target {
}
Reflect.defineMetadata(nestedClassType[metaType], newPath, NestedClass);
Reflect.defineProperty(NestedClass, "name", { value: target.name, writable: true });
return NestedClass;
}
}
exports.default = NestRouter;