UNPKG

@bestcodetools/api-node-base

Version:

BestCodeTools Node Base for Backend API

77 lines 2.74 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const handler_1 = __importDefault(require("../../../@types/interfaces/http/handler")); class HttpHandler { constructor(request, response, next, command) { this.request = request; this.response = response; this.next = next; this.command = command; this.setupHandlers(); } setupHandlers() { this.command.on('badRequest', this.onBadRequest.bind(this)); this.command.on('internalError', this.onInternalError.bind(this)); this.command.on('notImplemented', this.onNotImplemented.bind(this)); this.command.on('unprocessableEntity', this.onUnprocessableEntity.bind(this)); this.command.on('forbidden', this.onForbidden.bind(this)); this.command.on('unauthorized', this.onUnauthorized.bind(this)); this.command.on('success', this.onSuccess.bind(this)); this.command.on('created', this.onCreated.bind(this)); this.command.on('continue', this.next.bind(this)); } send(statusCode, body, headers) { const sendHeaders = { ...headers }; this.response.status(statusCode); Object.entries(sendHeaders).forEach(([key, value]) => { this.response.setHeader(key, value); }); if (body && typeof body === 'object') { this.response.json(body); } else if (['', null, undefined].includes(body)) { this.response.send(''); } else { this.response.send(body); } } onBadRequest(body, headers) { this.send(400, body, headers); } onUnprocessableEntity(body, headers) { this.send(422, body, headers); } onUnauthorized(body, headers) { this.send(401, body, headers); } onForbidden(body, headers) { this.send(403, body, headers); } onInternalError(body, headers) { this.send(500, body, headers); } onNotImplemented(body, headers) { this.send(501, body, headers); } onSuccess(body, headers) { this.send(200, body, headers); } onCreated(body, headers) { this.send(201, body, headers); } buildInput() { const headers = { ...this.request.headers }; const data = { ...this.request.query, ...this.request.body, ...this.request.params }; return { data, headers }; } async handle() { const payload = this.buildInput(); await this.command.execute(payload); } } exports.default = HttpHandler; //# sourceMappingURL=index.js.map