UNPKG

@x5e/gink

Version:

an eventually consistent database

64 lines 2.69 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Listener = void 0; const http_1 = require("http"); const https_1 = require("https"); const fs_1 = require("fs"); const websocket_1 = require("websocket"); const fs_2 = require("fs"); const utils_1 = require("./utils"); const path_1 = require("path"); /** * Just a utility class to wrap websocket.server. */ class Listener { constructor(args) { var _a; this.staticContentRoot = (_a = args.staticContentRoot) !== null && _a !== void 0 ? _a : (0, path_1.join)(__dirname, "../../content_root"); const requestListener = args.requestListener || this.requestListener.bind(this); const port = args.port || "8080"; let callWhenReady; this.index = args.index; this.ready = new Promise((resolve) => { callWhenReady = resolve; }); if (args.sslKeyFilePath && args.sslCertFilePath) { const options = { key: (0, fs_1.readFileSync)(args.sslKeyFilePath), cert: (0, fs_1.readFileSync)(args.sslCertFilePath), }; this.httpServer = (0, https_1.createServer)(options, requestListener).listen(port, () => { args === null || args === void 0 ? void 0 : args.logger(`Secure server is listening on port ${port}`); callWhenReady(); }); } else { this.httpServer = (0, http_1.createServer)(requestListener).listen(port, function () { args === null || args === void 0 ? void 0 : args.logger(`Insecure server is listening on port ${port}`); callWhenReady(); }); } this.websocketServer = new websocket_1.server({ httpServer: this.httpServer, }); this.websocketServer.on("request", args.requestHandler); } requestListener(request, response) { const url = new URL(request.url, `http://${request.headers.host}`); const requestedPath = url.pathname === "/" ? this.index : url.pathname; const localPath = (0, path_1.join)(this.staticContentRoot, requestedPath); if ((0, fs_2.existsSync)(localPath)) { const readStream = (0, fs_2.createReadStream)(localPath); const extension = (0, path_1.extname)(localPath).slice(1); response.writeHead(200, { "Content-type": (0, utils_1.getType)(extension) }); readStream.pipe(response); } else { response.writeHead(404, "Not Found"); response.end("not found"); } } } exports.Listener = Listener; //# sourceMappingURL=Listener.js.map