Repository navigation
Expand file tree
/
Copy pathdb.js
More file actions
57 lines (48 loc) · 1.38 KB
/
Copy pathdb.js
File metadata and controls
57 lines (48 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
'use strict';
require('dotenv').config();
const { MongoClient } = require('mongodb');
let client;
let connectionPromise;
async function getDatabase() {
if (!process.env.MONGODB_URI) {
throw new Error('MONGODB_URI is required to connect to MongoDB.');
}
if (!connectionPromise) {
try {
client = new MongoClient(process.env.MONGODB_URI);
} catch {
throw new Error(
'MongoDB connection failed. MONGODB_URI must be a valid MongoDB connection string.',
);
}
const connectingClient = client;
connectionPromise = connectingClient.connect()
.then(() => {
const database = connectingClient.db();
return {
database,
subscribers: database.collection('subscribers'),
reminders: database.collection('reminders'),
checkins: database.collection('checkins'),
};
})
.catch(() => {
client = undefined;
connectionPromise = undefined;
throw new Error(
'MongoDB connection failed. Check MONGODB_URI, Atlas network access, and database credentials.',
);
});
}
return connectionPromise;
}
async function closeDatabase() {
if (client) {
const connectedClient = client;
client = undefined;
connectionPromise = undefined;
await connectedClient.close();
}
}
module.exports = getDatabase;
module.exports.close = closeDatabase;