Skip to content

Commit

Permalink
fixed bug where initial check was false
Browse files Browse the repository at this point in the history
  • Loading branch information
LordFarquaadtheCreator committed Jun 13, 2024
1 parent cea5f85 commit 6f75b29
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 27 deletions.
56 changes: 30 additions & 26 deletions dbCheck.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,37 @@
import client from "./db.config";

async function getDB() {
await client.connect();
async function getDB(): Promise<void> {
await client.connect();
await client.end()
}

function runWithTimeout(fn: () => void, timeout: number, interval: number = 100) {
return new Promise<void>((resolve, reject) => {
const startTime = Date.now();

const handle = setInterval(() => {
const elapsedTime = Date.now() - startTime;

if (elapsedTime >= timeout) {
clearInterval(handle);
resolve();
} else {
try {
fn();
} catch (error) {
clearInterval(handle);
reject(error);
}
}
}, interval);
});
}
function runWithTimeout(fn: () => Promise<void>, timeout: number, interval: number) : Promise<void> {
return new Promise<void>((resolve, reject) => {
const startTime = Date.now();

const handle = setInterval(async () => {
const elapsedTime = Date.now() - startTime;

const args: string[] = process.argv;
const timeout: number = parseInt(args[2]);
if (elapsedTime >= timeout) {
clearInterval(handle);
resolve();
} else {
try {
await fn();
clearInterval(handle);
resolve();
} catch (error) {
clearInterval(handle);
reject(error);
}
}
}, interval);
});
}

await runWithTimeout(getDB, timeout);
runWithTimeout(getDB, parseInt(process.argv[2]), parseInt(process.argv[2]))
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
3 changes: 2 additions & 1 deletion server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,9 @@ let dbAval: boolean = true;

// initial check
try{
console.log(`Please wait ${TIMEOUT/1000}s for the database to connect`)
logger.info(`Please wait ${TIMEOUT/1000}s for the database to connect`)
dbAval = await checkDB(TIMEOUT);
logger.info("Server is up")
} catch (e: any) {
dbAval = false;
}
Expand Down

0 comments on commit 6f75b29

Please sign in to comment.