zents
Version:
ZenTS is a Node.js & TypeScript MVC-Framework for building rich web applications, released as free and open-source software under the MIT License. It is designed for building web applications with modern tools and design patterns.
73 lines • 3.36 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ControllerLoader = void 0;
const AbstractZenFileLoader_1 = require("../filesystem/AbstractZenFileLoader");
const joi_1 = __importDefault(require("joi"));
const enums_1 = require("../types/enums");
const FS_1 = require("../filesystem/FS");
const logger_1 = require("../log/logger");
class ControllerLoader extends AbstractZenFileLoader_1.AbstractZenFileLoader {
async load() {
const controllers = new Map();
const filePaths = (await FS_1.fs.readDir(FS_1.fs.resolveZenPath('controller'))).filter((filePath) => filePath.toLowerCase().endsWith(FS_1.fs.resolveZenFileExtension('controller')));
for (const filePath of filePaths) {
const { key, module } = await this.loadModule(filePath);
const keyMetadata = Reflect.getMetadata(enums_1.REFLECT_METADATA.CONTROLLER_KEY, module);
const controllerKey = typeof keyMetadata !== 'string' ? key : `${keyMetadata}Controller`.toLowerCase();
if (controllers.has(controllerKey)) {
logger_1.log.warn(`Controller with key "${controllerKey}" is already registered!`);
continue;
}
controllers.set(controllerKey, {
module,
routes: this.loadControllerRoutes(module),
});
}
return controllers;
}
loadControllerRoutes(classModule) {
const routes = [];
const methods = this.getClassMethods(classModule.prototype);
let prefix = Reflect.getMetadata(enums_1.REFLECT_METADATA.URL_PREFIX, classModule);
if (!prefix) {
prefix = '';
}
else if (prefix.endsWith('/')) {
prefix = prefix.slice(0, -1);
}
for (const method of methods) {
if (method === 'constructor') {
continue;
}
const httpMethod = Reflect.getMetadata(enums_1.REFLECT_METADATA.HTTP_METHOD, classModule.prototype, method);
if (typeof httpMethod !== 'string') {
continue;
}
const route = {
method: httpMethod.toUpperCase(),
path: '',
controllerMethod: method,
};
let urlPath = Reflect.getMetadata(enums_1.REFLECT_METADATA.URL_PATH, classModule.prototype, method);
if (prefix.length && !urlPath.startsWith('/')) {
urlPath = `/${urlPath}`;
}
route.path = `${prefix}${urlPath}`;
const authProvider = Reflect.getMetadata(enums_1.REFLECT_METADATA.AUTH_PROVIDER, classModule.prototype, method);
if (typeof authProvider === 'string') {
route.authProvider = authProvider;
}
const validationSchema = Reflect.getMetadata(enums_1.REFLECT_METADATA.VALIDATION_SCHEMA, classModule.prototype, method);
if (joi_1.default.isSchema(validationSchema)) {
route.validationSchema = validationSchema;
}
routes.push(route);
}
return routes;
}
}
exports.ControllerLoader = ControllerLoader;
//# sourceMappingURL=ControllerLoader.js.map