()
| 13 | let mongoClient: MongoClient; |
| 14 | |
| 15 | export async function connect(): Promise<void> { |
| 16 | const { |
| 17 | DB_USERNAME, |
| 18 | DB_PASSWORD, |
| 19 | DB_AUTH_MECHANISM, |
| 20 | DB_AUTH_SOURCE, |
| 21 | DB_URI, |
| 22 | DB_NAME, |
| 23 | } = process.env; |
| 24 | |
| 25 | const authProvided = |
| 26 | DB_USERNAME !== undefined && |
| 27 | DB_USERNAME !== "" && |
| 28 | DB_PASSWORD !== undefined && |
| 29 | DB_PASSWORD !== ""; |
| 30 | const uriProvided = DB_URI !== undefined && DB_URI !== ""; |
| 31 | const nameProvided = DB_NAME !== undefined && DB_NAME !== ""; |
| 32 | |
| 33 | if (!nameProvided || !uriProvided) { |
| 34 | throw new Error("No database configuration provided"); |
| 35 | } |
| 36 | |
| 37 | const auth = authProvided |
| 38 | ? { |
| 39 | username: DB_USERNAME, |
| 40 | password: DB_PASSWORD, |
| 41 | } |
| 42 | : undefined; |
| 43 | |
| 44 | const connectionOptions: MongoClientOptions = { |
| 45 | connectTimeoutMS: 2000, |
| 46 | serverSelectionTimeoutMS: 2000, |
| 47 | auth: auth, |
| 48 | authMechanism: DB_AUTH_MECHANISM as AuthMechanism | undefined, |
| 49 | authSource: DB_AUTH_SOURCE, |
| 50 | }; |
| 51 | |
| 52 | mongoClient = new MongoClient( |
| 53 | DB_URI ?? global.__MONGO_URI__, // Set in tests only |
| 54 | connectionOptions, |
| 55 | ); |
| 56 | |
| 57 | try { |
| 58 | await mongoClient.connect(); |
| 59 | db = mongoClient.db(DB_NAME); |
| 60 | } catch (error) { |
| 61 | Logger.error(getErrorMessage(error) ?? "Unknown error"); |
| 62 | Logger.error( |
| 63 | "Failed to connect to database. Exiting with exit status code 1.", |
| 64 | ); |
| 65 | process.exit(1); |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | export const getDb = (): Db | undefined => db; |
| 70 |
nothing calls this directly
no test coverage detected