node-microsvc-lib
Version:
NodeJS microservice framework library
175 lines • 8.64 kB
JavaScript
/**
* Created by pedrosousabarreto@gmail.com on 15/Jan/2019.
*/
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
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());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Microservice = void 0;
const http = __importStar(require("http"));
const assert_1 = __importDefault(require("assert"));
const express_1 = __importDefault(require("express"));
const Uuid = __importStar(require("uuid"));
const di_container_1 = require("./di_container");
const console_logger_1 = require("./console_logger");
class Microservice extends di_container_1.DiContainer {
constructor(configs, logger) {
super(logger);
this._run_express = true;
if (!logger)
this._logger = new console_logger_1.ConsoleLogger().create_child({ class: "Microservice" });
else
this._logger = logger.create_child({ class: "Microservice" });
console.time("MicroService - Start " + configs.instance_name);
//do something when app is closing
process.on('exit', () => {
this._logger.info("Microservice - exiting...");
});
//catches ctrl+c event
process.on('SIGINT', this._handle_int_and_term_signals.bind(this));
//catches program termination event
process.on('SIGTERM', this._handle_int_and_term_signals.bind(this));
this._configs = configs;
this.register_dependency("configs", this._configs);
}
init() {
return __awaiter(this, void 0, void 0, function* () {
// init configs first
yield this._configs.init();
const run_express_flag = this._configs.get_feature_flag_value("RUN_EXPRESS_APP");
this._run_express = run_express_flag == undefined ? true : run_express_flag;
if (this._run_express)
yield this._init_express_app();
yield this._init_factories();
console.timeEnd("MicroService - Start " + this._configs.instance_name);
});
}
destroy() {
return __awaiter(this, void 0, void 0, function* () {
let mod;
let factories_names = Array.from(this._factories.keys());
const all_destroys = factories_names.map((factory_name) => {
this._logger.info(`Microservice - destroying factory: ${factory_name}`);
mod = this.get(factory_name);
return mod.destroy();
});
yield Promise.all(all_destroys).catch((err) => {
this._logger.error(err, "Microservice - destroy cleanup error");
return Promise.reject(err);
}).then(() => {
this._logger.info("Microservice - destroy cleanup completed successfully, exiting...");
return Promise.resolve();
});
});
}
_init_express_app() {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve) => {
this._express_app = express_1.default();
this._port = this._configs.get_param_value("http_port");
assert_1.default(this._port, "Invalid port for express microservice");
this._http_server = http.createServer(this._express_app);
this._http_server.listen(this._port, "0.0.0.0");
this._http_server.on('error', this._http_error_handler.bind(this));
// register express_app and http_server in the DI Container
this.register_dependency("express_app", this._express_app);
this.register_dependency("http_server", this._http_server); // thanks jcfsantos
this._http_server.on('listening', () => {
let addr = this._http_server.address();
// let bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + JSON.stringify(addr);
this._logger.info(`Microservice - listening on: ${addr.family} ${addr.address}:${addr.port}`);
this._logger.info(`Microservice - PID: ${process.pid}`);
// hook health check - implement a proper health check with a factory
// this._express_app.get('/', this._health_check_handler.bind(this));
// debug
this._express_app.use("*", (req, res, next) => {
//console.log(`Got request - ${req.method} - ${req.originalUrl}`);
// TODO check for incoming correlationid header and set it from incoming
// add a correlation id to all calls
const correlation_id = Uuid.v4();
res.locals["correlation_id"] = correlation_id;
res.setHeader("X-API-correlation-id", correlation_id);
next();
});
// CORS
this._express_app.use(function (req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "HEAD, GET, POST, PATCH, DELETE");
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, X-Requested-With");
res.setHeader("access-control-expose-headers", "X-API-correlation-id");
next();
});
resolve();
});
});
});
}
_init_factories() {
return __awaiter(this, void 0, void 0, function* () {
let factories_names = Array.from(this._factories.keys());
let mod;
for (let i = 0; i < factories_names.length; i++) {
this._logger.info("Microservice - initializing factory: %s", factories_names[i]);
mod = this.get(factories_names[i]);
yield mod.init();
}
});
}
_http_error_handler(error) {
if (error["syscall"] !== 'listen')
throw error;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
this._logger.fatal(this._port + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
this._logger.fatal(this._port + ' is already in use');
process.exit(1);
break;
default:
this._logger.fatal("unkown error - ", error);
throw error;
}
}
_handle_int_and_term_signals(signal) {
return __awaiter(this, void 0, void 0, function* () {
this._logger.info(`Microservice - ${signal} received - cleaning up...`);
yield this.destroy()
.catch(err => process.exit(90))
.then(value => process.exit());
});
}
}
exports.Microservice = Microservice;
//# sourceMappingURL=microservice.js.map