UNPKG

briareus

Version:

Briareus assists with Feature Branch deploys to ECS

144 lines (122 loc) 3.02 kB
'use strict' const async = require('async'); const _ = require('lodash'); const EventEmitter = require('events'); const config = require('./config'); const logger = require('./logger'); const initializers = require('./initializers'); /* * Service Constructor * * @return {Object} An initialized Service application */ function Service(options) { if (!(this instanceof Service)) { return new Service(options); } this.running = false; this.events = new EventEmitter(); this.hooks = { start: [], stop: [], destroy: [] }; this.init(); } /* * Initialize the Service application */ Service.prototype.init = function () { this.config = config; this.log = logger; process.on('uncaughtException', (err) => { this.log.error({ 'err': err }); this.log.info('Exiting due to an uncaught exception'); process.exit(1); }); initializers.aws(this); initializers.routing(this); } Service.prototype.addHook = function (hook, description, fn) { this.hooks[hook].push({ description, fn }); } /* * Run registered hooks * * @param {String} Hook name * @param {Function} Callback */ Service.prototype.runHooks = function (hookName, cb) { this.log.debug(`Running hooks for "${hookName}"`); let hooks = _.map(this.hooks[hookName], (hook) => { return (done) => { this.log.debug(`Running "${hookName}" hook "${hook.description}"`); hook.fn((err) => { if (err) return done(err); this.log.debug(`Finished "${hookName}" hook "${hook.description}"`); done(); }); } }); async.applyEachSeries(hooks)(cb); } /* * Start the Service webserver * * @param {Function} Callback */ Service.prototype.start = function (cb) { if (this.running) return cb(); this.runHooks('start', (err) => { if (err) return cb(err); this.running = true; cb(); }); }; /* * Stop the Service webserver * * @param {Function} Callback */ Service.prototype.stop = function (cb) { if (!this.running) return cb(); this.runHooks('stop', (err) => { if (err) return cb(err); this.running = false; cb(); }); } /* * Destroy Service * * Stops the Service webserver and closes all database connections * * @param {Function} Callback */ Service.prototype.destroy = function (cb) { this.stop((err) => { if (err) return cb(err); this.runHooks('destroy', cb); }); } /* * Context * * Package application with context specific logger * * @param {Function} Callback */ // Service.prototype.context = function (req) { // let levels = ['fatal', 'error', 'warn', 'info', 'debug', 'trace']; // let contextLogger = _.zipObject(levels, _.map(levels, (level) => { // return (data, msg) => { // if (_.isString(data)) { // msg = data; // data = {}; // } // this.log[level](_.defaults(data, _.clone(req.context)), msg); // } // })); // return { // briareus: this, // log: contextLogger, // reqContext: req.context // }; // } module.exports = Service;