(mongodb: MongoClient)
| 402 | } |
| 403 | |
| 404 | async function ensureMongoPrimary(mongodb: MongoClient) { |
| 405 | const admin = mongodb.db("admin"); |
| 406 | |
| 407 | try { |
| 408 | await admin.command({ replSetGetStatus: 1 }); |
| 409 | } catch (error) { |
| 410 | if (isMongoError(error, "NotYetInitialized")) { |
| 411 | await admin.command({ replSetInitiate: mongoReplicaSetConfig }); |
| 412 | } else if ( |
| 413 | isMongoError(error, "InvalidReplicaSetConfig") || |
| 414 | (error instanceof Error && error.message.includes("not a member")) |
| 415 | ) { |
| 416 | await admin.command({ |
| 417 | replSetReconfig: mongoReplicaSetConfig, |
| 418 | force: true, |
| 419 | }); |
| 420 | } else { |
| 421 | throw error; |
| 422 | } |
| 423 | } |
| 424 | |
| 425 | for (let i = 0; i < 30; i++) { |
| 426 | const hello = await admin.command({ hello: 1 }); |
| 427 | if (hello.isWritablePrimary) return; |
| 428 | |
| 429 | await wait(500); |
| 430 | } |
| 431 | |
| 432 | throw new Error("Timed out waiting for MongoDB replica set primary."); |
| 433 | } |
| 434 | |
| 435 | export async function resetMongoDB(mongodb: MongoClient) { |
| 436 | await ensureMongoPrimary(mongodb); |
no test coverage detected