Skip to content

Commit dbfb84c

Browse files
Copilotimnasnainaec
andcommitted
Add startDatabase.js to .gitignore exceptions
Co-authored-by: imnasnainaec <6411521+imnasnainaec@users.noreply.github.com>
1 parent ca558a9 commit dbfb84c

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ scripts/*.js
3535
!scripts/frontendScripts.js
3636
!scripts/jestTest.js
3737
!scripts/setupMongo.js
38+
!scripts/startDatabase.js
3839
*.log
3940
*-debug.log*
4041
*-error.log*

scripts/startDatabase.js

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
"use strict";
2+
3+
const { spawn, spawnSync } = require("child_process");
4+
const { ensureDir } = require("fs-extra");
5+
6+
const dbPath = "./mongo_database";
7+
const replSetName = "rs0";
8+
const maxAttempts = 30;
9+
const retryInterval = 1000; // ms
10+
11+
async function waitForMongo() {
12+
for (let i = 0; i < maxAttempts; i++) {
13+
const result = spawnSync("mongosh", [
14+
"--eval",
15+
"db.adminCommand('ping')",
16+
"--quiet",
17+
]);
18+
if (result.status === 0) {
19+
return true;
20+
}
21+
await new Promise((resolve) => setTimeout(resolve, retryInterval));
22+
}
23+
return false;
24+
}
25+
26+
async function initReplicaSet() {
27+
const result = spawnSync(
28+
"mongosh",
29+
["--eval", "try { rs.status() } catch(e) { rs.initiate() }", "--quiet"],
30+
{ stdio: "inherit" }
31+
);
32+
return result.status === 0;
33+
}
34+
35+
async function main() {
36+
await ensureDir(dbPath);
37+
38+
const mongod = spawn("mongod", [`--dbpath=${dbPath}`, "--replSet", replSetName], {
39+
stdio: "inherit",
40+
});
41+
42+
mongod.on("error", (err) => {
43+
console.error(`mongod error: ${err.message}`);
44+
process.exit(1);
45+
});
46+
47+
const ready = await waitForMongo();
48+
if (ready) {
49+
await initReplicaSet();
50+
} else {
51+
console.error("MongoDB did not start in time");
52+
}
53+
54+
process.on("SIGINT", () => {
55+
mongod.kill("SIGINT");
56+
});
57+
process.on("SIGTERM", () => {
58+
mongod.kill("SIGTERM");
59+
});
60+
61+
await new Promise((resolve) => mongod.on("close", (code) => resolve(code)));
62+
}
63+
64+
main().catch((err) => {
65+
console.error(err);
66+
process.exit(1);
67+
});

0 commit comments

Comments
 (0)