forked from mrvautin/expressCart
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
62 lines (52 loc) · 1.66 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
const MongoClient = require('mongodb').MongoClient;
const mongodbUri = require('mongodb-uri');
let _db;
function initDb(dbUrl, callback){ // eslint-disable-line
if(_db){
console.warn('Trying to init DB again!');
return callback(null, _db);
}
MongoClient.connect(dbUrl, { useNewUrlParser: true, useUnifiedTopology: true }, connected);
function connected(err, client){
if(err){
console.log('Failed connecting to the DB', err);
return callback(err);
}
// Set the DB url
dbUrl = getDbUri(dbUrl);
// select DB
const dbUriObj = mongodbUri.parse(dbUrl);
// Set the DB depending on ENV
const db = client.db(dbUriObj.database);
// setup the collections
db.users = db.collection('users');
db.products = db.collection('products');
db.variants = db.collection('variants');
db.orders = db.collection('orders');
db.pages = db.collection('pages');
db.menu = db.collection('menu');
db.customers = db.collection('customers');
db.cart = db.collection('cart');
db.sessions = db.collection('sessions');
db.discounts = db.collection('discounts');
db.reviews = db.collection('reviews');
_db = db;
return callback(null, _db);
}
};
function getDbUri(dbUrl){
const dbUriObj = mongodbUri.parse(dbUrl);
// if in testing, set the testing DB
if(process.env.NODE_ENV === 'test'){
dbUriObj.database = 'expresscart-test';
}
return mongodbUri.format(dbUriObj);
}
function getDb(){
return _db;
}
module.exports = {
getDb,
initDb,
getDbUri
};