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.
61 lines • 2.57 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ControllerRequestHandler = void 0;
const TemplateResponse_1 = require("../../template/TemplateResponse");
const isObject_1 = require("../../utils/isObject");
class ControllerRequestHandler {
constructor(context, controllerFactory, controllerKey, loadedUser, { controllerMethod }) {
this.context = context;
this.loadedUser = loadedUser;
this.didRun = false;
this.controllerInstance = controllerFactory.build(controllerKey);
this.controllerMethod = controllerMethod;
this.injector = controllerFactory.getInjector();
}
async run() {
if (this.didRun) {
return;
}
else if (typeof this.controllerInstance[this.controllerMethod] !== 'function') {
throw new Error(`Fatal Error: ${this.controllerMethod} isn't a function.`);
}
this.didRun = true;
const injectedSessions = [];
const injectedParameters = await this.injector.injectFunctionParameters(this.controllerInstance, this.controllerMethod, this.context, this.loadedUser, injectedSessions);
const result = await this.controllerInstance[this.controllerMethod](...injectedParameters);
if (!this.context.res.isSend) {
this.handleResult(result);
}
await this.saveSessionStores(injectedSessions);
}
handleResult(result) {
if (!result) {
return;
}
if (this.context.req.httpMethod === 'post' && !this.context.res.isStatuscodeSetManual) {
this.context.res.setStatusCode(201);
}
if (result instanceof TemplateResponse_1.TemplateResponse) {
return this.context.res.html(result.html).send();
}
else if (isObject_1.isObject(result)) {
return this.context.res.json(result).send();
}
else if (Array.isArray(result)) {
return this.context.res.json(result).send();
}
else if (typeof result === 'string') {
return this.context.res.text(result).send();
}
else {
return this.context.error.internal('Controller returned an unsupported value. Please return an object, an array or a string.');
}
}
async saveSessionStores(injectedSessions) {
for (const session of injectedSessions) {
await session.data.save();
}
}
}
exports.ControllerRequestHandler = ControllerRequestHandler;
//# sourceMappingURL=ControllerRequestHandler.js.map