UNPKG

airship-server

Version:

Airship is a framework for Node.JS & TypeScript that helps you to write big, scalable and maintainable API servers.

48 lines 2.2 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const RequestsProvider_1 = require("../domain/RequestsProvider"); const ASErrorResponse_1 = require("../domain/entity/ASErrorResponse"); const JSONSerializer_1 = require("../../serialize/JSONSerializer"); const Diet = require('diet'); class HttpRequestsProvider extends RequestsProvider_1.RequestsProvider { constructor(logger, port, ...supportedRequests) { super(); this._logger = logger; this._supportedRequests = supportedRequests; this._requestsCallback = null; const app = Diet({ silent: true }); this._app = app; app.listen(`127.0.0.1:${port}`); this._logger.log('HttpRequestsProvider', `Started listening at 127.0.0.1:${port}`); this._logger.log('HttpRequestsProvider supported requests:\n', supportedRequests .map(r => r.prototype.constructor.name) .join('\n')); this._supportedRequests.forEach(request => { let queryPath = request.getQueryPath(); this.setupMethod(request, 'post', queryPath); }); } getRequests(callback) { this._requestsCallback = callback; } setupMethod(request, type, path) { this._app[type](path, ($) => { if (!this._requestsCallback) throw new Error('No request callback'); try { let data = type == 'post' ? $.body : $.query; if (!data) $.end(JSON.stringify(JSONSerializer_1.default.serialize(new ASErrorResponse_1.default('No data passed')))); let deserializedRequest = JSONSerializer_1.default.deserialize(request, type == 'post' ? $.body : $.query); this._requestsCallback(deserializedRequest, (response) => { $.end(JSON.stringify(JSONSerializer_1.default.serialize(response))); }); } catch (e) { $.end(JSON.stringify(JSONSerializer_1.default.serialize(new ASErrorResponse_1.default(e.message)))); } }); } } exports.default = HttpRequestsProvider; //# sourceMappingURL=HttpRequestsProvider.js.map