-
Notifications
You must be signed in to change notification settings - Fork 0
/
gracefull-stop.mjs
37 lines (31 loc) · 1.04 KB
/
gracefull-stop.mjs
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
export function registerGracefulShutdown(consumers, callback) {
const errorTypes = ['unhandledRejection', 'uncaughtException'];
const signalTraps = ['SIGTERM', 'SIGINT', 'SIGUSR2'];
errorTypes.forEach(type => {
process.on(type, async e => {
try {
console.log(`process.on ${type}`);
console.error(e);
await Promise.allSettled(consumers.map((consumer) => consumer.disconnect()));
if (callback) {
await callback()
}
process.exit(0);
} catch (_) {
process.exit(1);
}
});
});
signalTraps.forEach(type => {
process.once(type, async () => {
try {
await Promise.allSettled(consumers.map((consumer) => consumer.disconnect()));
if (callback) {
await callback()
}
} finally {
process.kill(process.pid, type);
}
});
});
}