Skip to content

Commit

Permalink
fix: await async stop
Browse files Browse the repository at this point in the history
  • Loading branch information
mfw78 committed Oct 6, 2023
1 parent ec69080 commit b60c7d5
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 10 deletions.
23 changes: 15 additions & 8 deletions src/commands/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ export async function run(options: RunOptions) {

process.on("unhandledRejection", async (error) => {
log.error("Unhandled promise rejection", error);
stop(1);
await stop(1);
});

process.on("SIGINT", async function () {
log.info("Caught interrupt signal.");
stop();
await stop();
});

let exitCode = 0;
Expand Down Expand Up @@ -54,20 +54,27 @@ export async function run(options: RunOptions) {
log.error("Unexpected error thrown when running watchtower", error);
exitCode = 1;
} finally {
stop(exitCode);
await stop(exitCode);
}
}

/**
* Run actions required when stopping the watch-tower from run mode
* @param exitCode Exit code to return to the shell
*/
function stop(exitCode?: number) {
async function stop(exitCode?: number) {
const log = getLogger("commands:stop");
log.info("Stopping Rest API server...");
ApiService.getInstance().stop();
log.info("Closing database...");
DBService.getInstance().close();
const stopServices = [
ApiService.getInstance().stop(),
DBService.getInstance().close(),
];
await Promise.allSettled(stopServices).then((results) => {
results.forEach((result) => {
if (result.status === "rejected") {
log.error("Error stopping service", result.reason);
}
});
});
log.info("Exiting watchtower...");
process.exit(exitCode || 0);
}
4 changes: 2 additions & 2 deletions src/utils/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ export class ApiService {
throw new Error("Server is not running");
}

const log = getLogger("api");
log.info("Stopping Rest API server");
const log = getLogger("api:stop");
log.info("Stopping Rest API server...");

this.server.once("close", resolve);
this.server.close();
Expand Down
3 changes: 3 additions & 0 deletions src/utils/db.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { DatabaseOptions, Level } from "level";
import { getLogger } from "./logging";

const DEFAULT_DB_LOCATION = "./database";

Expand Down Expand Up @@ -34,6 +35,8 @@ export class DBService {
}

public async close() {
const log = getLogger("dbService:close");
log.info("Closing database...");
await this.db.close();
}

Expand Down

0 comments on commit b60c7d5

Please sign in to comment.