inceptum
Version:
hipages take on the foundational library for enterprise-grade apps written in NodeJS
77 lines • 3.26 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const Context_1 = require("../ioc/Context");
const LogManager_1 = require("../log/LogManager");
const PreinstantiatedSingletonDefinition_1 = require("../ioc/objectdefinition/PreinstantiatedSingletonDefinition");
const Lifecycle_1 = require("../ioc/Lifecycle");
const ConfigProvider_1 = require("../config/ConfigProvider");
class BaseApp {
/**
* Creates a new Inceptum App
*/
constructor(options = {}) {
this.plugins = [];
this.pluginContext = new Map();
const { config = new ConfigProvider_1.default() } = options;
const { logger = LogManager_1.LogManager.getLogger(__filename) } = options;
this.logger = logger;
this.logger.info(`Using app name ${LogManager_1.LogManager.getAppName()}`);
this.context = new Context_1.Context(config.getConfig('app.context.name', 'BaseContext'), null, options);
this.context.registerDefinition(new PreinstantiatedSingletonDefinition_1.PreinstantiatedSingletonDefinition(LogManager_1.LogManager));
this.context.registerDefinition(new PreinstantiatedSingletonDefinition_1.PreinstantiatedSingletonDefinition(logger, 'logger'));
this.context.on('STOPPED', () => LogManager_1.LogManager.scheduleShutdown());
}
use(...plugins) {
return this.register(...plugins);
}
addDirectory(path) {
return this.getContext().registerSingletonsInDir(path);
}
register(...plugins) {
if (this.context.getStatus() !== Lifecycle_1.LifecycleState.NOT_STARTED) {
throw new Error(`Cannot register plugin(s) ${plugins
.map((p) => p.name)
.join(',')} as the app has already started. Please register all plugins before calling "start()"`);
}
this.plugins = this.plugins.concat(plugins);
}
runLifecycleMethodOnPlugins(method) {
return this.plugins.reduce(async (previous, plugin) => {
await previous;
if (plugin[method]) {
this.logger.debug(`${method}:${plugin.name}`);
return plugin[method](this, this.pluginContext);
}
return Promise.resolve();
}, Promise.resolve());
}
async start() {
await this.runLifecycleMethodOnPlugins('willStart');
process.on('SIGINT', () => {
this.stop().then(() => process.exit());
});
await this.context.lcStart();
return await this.runLifecycleMethodOnPlugins('didStart');
}
async stop() {
await this.runLifecycleMethodOnPlugins('willStop');
this.logger.info('Shutting down app');
await this.context.lcStop();
const r = await this.runLifecycleMethodOnPlugins('didStop');
delete this.logger;
return r;
}
getContext() {
return this.context;
}
// tslint:disable-next-line:prefer-function-over-method
getConfig(key, defaultValue) {
return this.getContext().getConfig(key, defaultValue);
}
// tslint:disable-next-line:prefer-function-over-method
hasConfig(key) {
return this.getContext().hasConfig(key);
}
}
exports.default = BaseApp;
//# sourceMappingURL=BaseApp.js.map