Skip to content

Commit

Permalink
fix: Improve graceful shutdown
Browse files Browse the repository at this point in the history
  • Loading branch information
schw4rzlicht committed Jun 8, 2020
1 parent 56fd884 commit 626430d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 13 deletions.
4 changes: 2 additions & 2 deletions __tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
27 changes: 16 additions & 11 deletions src/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -114,9 +106,22 @@ export async function loadConfig(configFile: string): Promise<Config> {
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 {
Expand Down

0 comments on commit 626430d

Please sign in to comment.