All files / src App.ts

99.17% Statements 120/121
85.22% Branches 75/88
96.77% Functions 30/31
99.13% Lines 115/116

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247          1x 1x 1x 1x 1x 1x 1x                             1x   26x 26x 26x   26x     26x 26x       26x 26x 26x 26x   26x 26x 26x         1x       1x             18x   18x 21x 21x 21x 1x     20x   20x     17x   17x 19x 19x 18x     16x 18x 18x   16x 16x 16x       1x 1x 1x     16x             3x   3x 1x 2x 2x     3x   3x       18x   18x 1x 1x       18x 18x   18x 18x 1x 1x 1x 1x 1x     18x 18x 14x 14x 12x     16x   2x 2x 2x         25x 25x   25x   25x 25x 24x 20x 20x 20x 19x   1x     24x   1x 1x         4x       4x 4x 3x     1x       2x       1x   1x 1x   1x           1x       26x 26x 552x 531x 531x     21x   21x 21x 19x 19x   2x     26x 54x     26x                     13x  
/*
 * © Copyright 2022 HP Development Company, L.P.
 * SPDX-License-Identifier: MIT
 */
 
import pino, { Level, Logger } from 'pino';
import { ClassType, reflect } from '@davinci/reflector';
import deepmerge from 'deepmerge';
import { Module, ModuleStatus } from './Module';
import { mapSeries } from './lib/async-utils';
import { coerceArray } from './lib/array-utils';
import { di } from './di';
import { LocalVars, LocalVarsContainer, Signals } from './types';
 
export interface AppOptions {
	controllers?: ClassType[];
	shutdown?: {
		enabled?: boolean;
		signals?: Signals[];
	};
	logger?: {
		name?: string;
		level?: Level | 'silent';
	};
}
 
export class App extends Module implements LocalVarsContainer {
	logger: Logger;
	public locals: LocalVars = {};
	private options?: AppOptions = {};
	private modules: Module[] = [];
	private controllers: ClassType[];
	private modulesDic: Record<string, Module> = {};
 
	constructor(options?: AppOptions) {
		super();
		const defaultOptions: AppOptions = {
			shutdown: { enabled: true, signals: ['SIGTERM', 'SIGINT'] },
			logger: { name: 'app', level: 'info' }
		};
		this.options = deepmerge({ ...defaultOptions }, { ...options });
		this.controllers = options?.controllers ?? [];
		Eif (this.options.shutdown?.enabled) {
			this.enableShutdownSignals();
		}
		this.logger = pino({ name: this.options.logger?.name });
		Eif (this.options.logger?.level) {
			this.logger.level = this.options.logger?.level;
		}
	}
 
	public getModuleId(): string {
		return 'app';
	}
 
	public getOptions() {
		return this.options;
	}
 
	public async registerModule(module: Module): Promise<this>;
	public async registerModule(modules: Module[]): Promise<this>;
	public async registerModule(...modules: Module[]): Promise<this>;
	public async registerModule(...args: Array<unknown>) {
		const modules = coerceArray(args.length > 1 ? args : args[0]) as Module[];
 
		modules.forEach(mod => {
			const moduleIds = coerceArray(mod.getModuleId());
			moduleIds.forEach(id => {
				if (this.modulesDic[id]) {
					throw new Error(`A module with the same identifier "${id}" has already been registered`);
				}
 
				this.modulesDic[id] = mod;
			});
			this.modules.push(mod);
		});
 
		this.setStatus('registering');
 
		await mapSeries(modules, async mod => {
			mod.setStatus('registering');
			await mod.onRegister?.(this);
			mod.setStatus('registered');
		})
			.then(() => {
				const allModulesRegistered = Object.keys(this.modulesDic)
					.map(key => this.modulesDic[key].getStatus())
					.every(status => status === 'registered');
 
				Eif (allModulesRegistered) {
					this.setStatus('registered');
					this.eventBus.emit('registered');
				}
			})
			.catch(err => {
				this.logger.fatal({ error: err }, 'Fatal error during module registration');
				this.setStatus('error');
				throw err;
			});
 
		return this;
	}
 
	public registerController(controllers: ClassType[]): this;
	public registerController(...controllers: ClassType[]): this;
	public registerController(controller: ClassType): this;
	public registerController(...args: any[]) {
		let controllers: ClassType[] = [];
 
		if (args.length > 1) {
			controllers = args;
		} else Eif (args) {
			controllers = coerceArray(args[0]);
		}
 
		this.controllers.push(...controllers);
 
		return this;
	}
 
	public async init() {
		const appStatus = this.getStatus();
 
		if (appStatus === 'registering') {
			await new Promise(resolve => {
				this.eventBus.once('registered', () => resolve(null));
			});
		}
 
		this.logger.debug('App initialization. Executing onInit hooks');
		this.setStatus('initializing');
 
		try {
			if (appStatus === 'error' || appStatus === 'destroyed') {
				this.logger.debug(`Automatically executing the onRegister hooks as the App status is: ${appStatus}`);
				const modulesCopy = [...this.modules];
				this.modules = [];
				this.modulesDic = {};
				await this.registerModule(modulesCopy);
			}
 
			await this.onInit?.(this);
			await mapSeries(this.modules, async module => {
				module.setStatus('initializing');
				await module.onInit?.(this);
				module.setStatus('initialized');
			});
 
			this.setStatus('initialized');
		} catch (err) {
			this.logger.fatal({ error: err }, 'Fatal error during module init');
			this.setStatus('error');
			throw err;
		}
	}
 
	public async shutdown() {
		this.logger.debug('App shutdown. Executing onDestroy hooks');
		this.setStatus('destroying');
 
		const wrapIntoPromise = async (fn: Function) => fn();
 
		try {
			await this.onDestroy?.(this);
			await mapSeries(this.modules, async module => {
				try {
					module.setStatus('destroying');
					await wrapIntoPromise(() => module.onDestroy?.(this));
					module.setStatus('destroyed');
				} catch (err) {
					this.logger.error({ moduleId: module.getModuleId(), error: err }, 'Error while destroying module');
				}
			});
			this.setStatus('destroyed');
		} catch (err) {
			this.logger.fatal({ error: err }, 'Fatal error');
			throw err;
		}
	}
 
	public getModules() {
		return this.modules;
	}
 
	public async getModuleById<M extends Module = Module>(moduleId: string, waitForStatus?: ModuleStatus): Promise<M> {
		const module = this.modulesDic[moduleId];
		if (waitForStatus) {
			return (await module.waitForStatus(waitForStatus)) as M;
		}
 
		return module as M;
	}
 
	public getControllers() {
		return this.controllers;
	}
 
	public getControllersWithReflection() {
		return (
			this.controllers?.map(Controller => {
				const controllerReflection = this.getControllerReflection(Controller);
				const controllerInstance = di.container.resolve(Controller);
 
				return { Controller, controllerInstance, reflection: controllerReflection };
			}) ?? []
		);
	}
 
	public getControllerReflection(controller: ClassType) {
		return reflect(controller);
	}
 
	public enableShutdownSignals() {
		const signals = this.options?.shutdown?.signals ?? [];
		const onSignal = async (signal: Signals) => {
			if (['destroying', 'destroyed'].includes(this.getStatus())) {
				this.logger.debug('App is already shutting down. Ignoring signal');
				return;
			}
 
			this.logger.info(`Received ${signal}, shutting down`);
 
			try {
				await this.shutdown();
				process.kill(process.pid, signal);
				process.exit(0);
			} catch (err) {
				process.exit(1);
			}
		};
		signals.forEach(signal => {
			process.on(signal, onSignal);
		});
 
		return this;
	}
 
	public addLocalVariable<T>(name: string, value: T) {
		Object.defineProperty(this.locals, name, {
			configurable: true,
			value
		});
	}
}
 
export const createApp = (options?: AppOptions) => new App(options);