lisk-framework
Version:
Lisk blockchain application platform
61 lines • 2.4 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HTTPServer = void 0;
const HTTP = require("http");
const ALLOWED_METHOD = 'POST';
class HTTPServer {
constructor(options) {
var _a, _b, _c;
this._host = options.host;
this._port = options.port;
this._path = (_a = options.path) !== null && _a !== void 0 ? _a : '/rpc';
this._ignorePaths = (_b = options.ignorePaths) !== null && _b !== void 0 ? _b : [];
this._accessControlAllowOrigin = (_c = options.accessControlAllowOrigin) !== null && _c !== void 0 ? _c : '*';
}
start(logger, httpRequestListener) {
this._logger = logger;
this.server = HTTP.createServer(async (req, res) => {
var _a;
if (this._ignorePaths.some(v => v === req.url)) {
return undefined;
}
const headers = {
'Access-Control-Allow-Origin': this._accessControlAllowOrigin,
'Access-Control-Allow-Methods': ALLOWED_METHOD,
'Content-Type': 'application/json',
};
if (req.url !== this._path) {
res.writeHead(404, headers);
return res.end(`${(_a = req.url) !== null && _a !== void 0 ? _a : ''} not found.`);
}
if (req.method === ALLOWED_METHOD) {
res.writeHead(200, headers);
const buffers = [];
for await (const chunks of req) {
buffers.push(chunks);
}
const message = Buffer.concat(buffers).toString();
return httpRequestListener(req, res, message);
}
res.writeHead(405, headers);
return res.end(`${req.method} is not allowed for the request.`);
});
this.server.on('error', err => {
this._logger.error({ err }, 'Error on HTTP server');
});
return this.server;
}
stop() {
if (this.server) {
this.server.close();
}
}
listen() {
this.server.listen(this._port, this._host, () => {
var _a;
this._logger.info(`RPC HTTP Server starting at ${(_a = this._host) !== null && _a !== void 0 ? _a : ''}:${this._port}${this._path}`);
});
}
}
exports.HTTPServer = HTTPServer;
//# sourceMappingURL=http_server.js.map