tree-house
Version:
NodeJS utilities and handy helpers extending ExpressJS functionalities
81 lines (80 loc) • 3.37 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.postHook = exports.preHook = exports.startServer = void 0;
const http = require("http");
const https = require("https");
const fs = require("fs");
function startServer(app, options) {
return __awaiter(this, void 0, void 0, function* () {
try {
if (options.pre)
yield preHook(options.pre);
const httpServer = http.createServer(app);
httpServer.listen(options.port);
console.log(`${options.title || 'TreeHouse'} HTTP NodeJS Server listening on port ${options.port}`);
if (options.https) {
const httpsServer = https.createServer(getHttpsCredentials(options.https.certificate, options.https.privateKey), app);
if (options.headersTimeout)
httpsServer.headersTimeout = options.headersTimeout;
if (options.keepAliveTimeout)
httpsServer.keepAliveTimeout = options.keepAliveTimeout;
httpsServer.listen(options.https.port);
console.log(`${options.title || 'TreeHouse'} HTTPS NodeJS Server listening on port ${options.https.port}`);
}
if (options.headersTimeout)
httpServer.headersTimeout = options.headersTimeout;
if (options.keepAliveTimeout)
httpServer.keepAliveTimeout = options.keepAliveTimeout;
if (options.post)
yield postHook(options.post, httpServer);
}
catch (error) {
console.error('An error occurred trying to start the server:\n', error.message);
throw error;
}
});
}
exports.startServer = startServer;
function preHook(fn) {
return __awaiter(this, void 0, void 0, function* () {
try {
yield fn();
}
catch (error) {
console.error('Error trying to execute the pre-hook function');
throw error;
}
});
}
exports.preHook = preHook;
function postHook(fn, httpServer) {
return __awaiter(this, void 0, void 0, function* () {
try {
yield fn(httpServer);
}
catch (error) {
console.error('Error trying to execute the post-hook function');
throw error;
}
});
}
exports.postHook = postHook;
function getHttpsCredentials(certificate, privateKey) {
try {
const key = fs.readFileSync(privateKey, 'utf8');
const cert = fs.readFileSync(certificate, 'utf8');
return { key, cert };
}
catch (e) {
throw new Error(`Something went wrong while fetching keys: ${e}`);
}
}