This commit is contained in:
syuilo
2022-02-04 11:10:53 +09:00
parent 73de9be6d5
commit bd7662e5e4
7 changed files with 29 additions and 20 deletions

View File

@ -24,14 +24,14 @@ const SHUTDOWN_TIMEOUT = 15000;
* down the process.
* @type {BeforeShutdownListener[]}
*/
const shutdownListeners = [];
const shutdownListeners: ((signalOrEvent: string) => void)[] = [];
/**
* Listen for signals and execute given `fn` function once.
* @param {string[]} signals System signals to listen to.
* @param {function(string)} fn Function to execute on shutdown.
*/
const processOnce = (signals, fn) => {
const processOnce = (signals: string[], fn: (signalOrEvent: string) => void) => {
for (const sig of signals) {
process.once(sig, fn);
}
@ -41,7 +41,7 @@ const processOnce = (signals, fn) => {
* Sets a forced shutdown mechanism that will exit the process after `timeout` milliseconds.
* @param {number} timeout Time to wait before forcing shutdown (milliseconds)
*/
const forceExitAfter = timeout => () => {
const forceExitAfter = (timeout: number) => () => {
setTimeout(() => {
// Force shutdown after timeout
console.warn(`Could not close resources gracefully after ${timeout}ms: forcing shutdown`);
@ -55,7 +55,7 @@ const forceExitAfter = timeout => () => {
* be logged out as a warning, but won't prevent other callbacks from executing.
* @param {string} signalOrEvent The exit signal or event name received on the process.
*/
async function shutdownHandler(signalOrEvent) {
async function shutdownHandler(signalOrEvent: string) {
if (process.env.NODE_ENV === 'test') return process.exit(0);
console.warn(`Shutting down: received [${signalOrEvent}] signal`);
@ -64,7 +64,9 @@ async function shutdownHandler(signalOrEvent) {
try {
await listener(signalOrEvent);
} catch (err) {
console.warn(`A shutdown handler failed before completing with: ${err.message || err}`);
if (err instanceof Error) {
console.warn(`A shutdown handler failed before completing with: ${err.message || err}`);
}
}
}
@ -78,7 +80,7 @@ async function shutdownHandler(signalOrEvent) {
* @param {BeforeShutdownListener} listener The shutdown listener to register.
* @returns {BeforeShutdownListener} Echoes back the supplied `listener`.
*/
export function beforeShutdown(listener) {
export function beforeShutdown(listener: () => void) {
shutdownListeners.push(listener);
return listener;
}