forked from harness-community/MERN-Stack-Example
-
Notifications
You must be signed in to change notification settings - Fork 2
/
db.js
36 lines (32 loc) · 838 Bytes
/
db.js
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
import { MongoClient } from 'mongodb';
import { MongoMemoryServer } from 'mongodb-memory-server';
export default class MongoConnection {
mongoDBConnectionOptions = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
dbURI;
db;
static async connectDb() {
if (process.env.NODE_ENV === 'test') {
this.dbURI = await (await MongoMemoryServer.create()).getUri();
} else {
this.dbURI = process.env.ATLAS_URI;
}
if (this.db) {
return this.db;
} else {
try {
const newDbClient = await MongoClient.connect(
this.dbURI,
this.mongoDBConnectionOptions
);
this.db = newDbClient;
return newDbClient;
} catch (error) {
console.error(`MongoDB connection failed with > ${error}`);
throw error;
}
}
}
}