From 626430d16e8ec9eda9ce27aaa8f0a8a909ef47b0 Mon Sep 17 00:00:00 2001 From: Julian Rabe Date: Mon, 8 Jun 2020 13:47:44 +0200 Subject: [PATCH] fix: Improve graceful shutdown --- __tests__/index.test.ts | 4 ++-- src/lib/index.ts | 27 ++++++++++++++++----------- 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/__tests__/index.test.ts b/__tests__/index.test.ts index f226f7d..8c7547c 100644 --- a/__tests__/index.test.ts +++ b/__tests__/index.test.ts @@ -94,14 +94,14 @@ test("Invalid config", async () => { restoreConfigFile(configTmp); }); -test("Exit with error", () => { +test("Exit with error", async () => { let consoleSpy = jest.spyOn(console, "error").mockImplementationOnce(() => {}); // @ts-ignore let exitSpy = jest.spyOn(process, "exit").mockImplementationOnce(() => {}); - index.exitWithError(new Error("Fuck dat!")); + await expect(index.exitWithError(new Error("Fuck dat!"))).resolves.toBeUndefined(); expect(consoleSpy).toHaveBeenCalledWith(expect.stringMatching("Fuck dat! Exiting...")); expect(exitSpy).toHaveBeenCalledWith(1); diff --git a/src/lib/index.ts b/src/lib/index.ts index bf3f8da..a9cc48e 100644 --- a/src/lib/index.ts +++ b/src/lib/index.ts @@ -16,15 +16,7 @@ export async function main() { process.on("SIGINT", () => { console.log(chalk`\n{bold Thank you for using twitch2ma} ❤️`); - if(twitch2Ma) { - twitch2Ma.stop() - .then(() => process.exit(0)) - .catch((err: Error) => { - error(err.message); - process.exit(1); - }) - } - process.exit(0); + exit(0); }); return require("libnpm") @@ -114,9 +106,22 @@ export async function loadConfig(configFile: string): Promise { return new Config(rawConfigObject); } -export function exitWithError(err: Error) { +async function exit(statusCode: number) { + let stopPromise = Promise.resolve(); + if(twitch2Ma) { + stopPromise + .then(() => twitch2Ma.stop()) + .catch((err: Error) => { + error(err.message); + process.exit(1); + }) + } + return stopPromise.then(() => process.exit(statusCode)); +} + +export async function exitWithError(err: Error) { error((err.message.slice(-1) === "!" ? err.message : err.message + "!") + " Exiting..."); - process.exit(1); + return exit(1); } function channelMessage(channel: string, message: string): void {