-
Notifications
You must be signed in to change notification settings - Fork 41
/
db.js
90 lines (79 loc) · 2.2 KB
/
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// import config file
const config = require('./config');
// mongodb driver
const MongoClient = require("mongodb").MongoClient;
if (!config.mongo_db_connection_string) {
throw Error("⚠ ⚠ ⚠ Put connection string from MongoDB Atlas in .env file ⚠ ⚠ ⚠")
}
class DbConnection {
constructor() {
this.db = null;
this.dbName = "data";
this.url = process.env.MONGO_DB_CONNECTION_STRING;
this.options = {
useNewUrlParser: true,
useUnifiedTopology: true
};
this.collections = {};
}
connectWithCallback(successCallback, failureCallback) {
if (this.db) {
successCallback(this.db);
} else {
MongoClient.connect(this.url, this.options, (err, dbInstance) => {
if (err) {
console.log(`[MongoDB connection] ERROR: ${err}`);
failureCallback(err); // caught by the calling function
} else {
const dbObject = dbInstance.db(this.dbName);
console.log("[MongoDB connection] SUCCESS");
this.db = dbObject;
successCallback(dbObject);
}
});
}
}
connectWithPromise() {
if (this.db) {
return Promise.resolve(this.db);
} else {
return new Promise((resolve, reject) => {
MongoClient.connect(this.url, this.options, (err, dbInstance) => {
if (err) {
console.log(`[MongoDB connection] ERROR: ${err}`);
// failureCallback(err); // caught by the calling function
reject(err);
} else {
const dbObject = dbInstance.db(this.dbName);
console.log("[MongoDB connection] SUCCESS");
this.db = dbObject;
// successCallback(dbObject);
resolve(dbObject);
}
});
})
}
}
async getCollection(collectionName) {
if (this.collections[collectionName]) {
return this.collections[collectionName];
} else {
let dbObject;
try {
dbObject = await this.connectWithPromise();
} catch (db_error) {
throw db_error;
}
const dbCollection = dbObject.collection(collectionName);
// TESTING: get all items in this collection and log
dbCollection.find().toArray((err, result) => {
if (err) throw err;
// console.log(result);
});
this.collections[collectionName] = dbCollection;
return dbCollection;
}
};
};
const dbConnection = new DbConnection();
module.exports = dbConnection;