-
-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathprocess-service.ts
43 lines (35 loc) · 1.14 KB
/
process-service.ts
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
export class ProcessService implements IProcessService {
private static PROCESS_EXIT_SIGNALS = ["exit", "SIGINT", "SIGTERM"];
private _listeners: IListener[];
public get listenersCount(): number {
return this._listeners.length;
}
constructor() {
this._listeners = [];
}
public attachToProcessExitSignals(context: any, callback: () => void): void {
const callbackToString = callback.toString();
if (this._listeners.length === 0) {
_.each(ProcessService.PROCESS_EXIT_SIGNALS, (signal: NodeJS.Signals) => {
process.on(signal, () => this.executeAllCallbacks.apply(this));
});
}
if (!_.some(this._listeners, (listener: IListener) => context === listener.context && callbackToString === listener.callback.toString())) {
this._listeners.push({ context, callback });
}
}
private executeAllCallbacks(): void {
_.each(this._listeners, (listener: IListener) => {
try {
listener.callback.apply(listener.context);
} catch (err) {
// ignore the error and let other handlers to be called.
}
});
}
}
interface IListener {
context: any;
callback: () => void;
}
$injector.register("processService", ProcessService);