2019-06-08 17:49:40 +10:00
|
|
|
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);
|
|
|
|
}
|
2019-10-29 17:57:06 +10:00
|
|
|
MongoClient.connect(dbUrl, { useNewUrlParser: true, useUnifiedTopology: true }, connected);
|
2019-06-08 17:49:40 +10:00
|
|
|
function connected(err, client){
|
|
|
|
if(err){
|
|
|
|
return callback(err);
|
|
|
|
}
|
|
|
|
|
2020-01-21 17:36:46 +10:00
|
|
|
// Set the DB url
|
|
|
|
dbUrl = getDbUri(dbUrl);
|
|
|
|
|
2019-06-08 17:49:40 +10:00
|
|
|
// select DB
|
|
|
|
const dbUriObj = mongodbUri.parse(dbUrl);
|
2020-01-21 17:36:46 +10:00
|
|
|
|
|
|
|
// Set the DB depending on ENV
|
|
|
|
const db = client.db(dbUriObj.database);
|
2019-06-08 17:49:40 +10:00
|
|
|
|
|
|
|
// setup the collections
|
|
|
|
db.users = db.collection('users');
|
|
|
|
db.products = db.collection('products');
|
|
|
|
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');
|
2020-01-21 17:36:46 +10:00
|
|
|
db.discounts = db.collection('discounts');
|
2019-06-08 17:49:40 +10:00
|
|
|
|
|
|
|
_db = db;
|
|
|
|
return callback(null, _db);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2020-01-21 17:36:46 +10:00
|
|
|
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);
|
|
|
|
}
|
|
|
|
|
2019-06-08 17:49:40 +10:00
|
|
|
function getDb(){
|
|
|
|
return _db;
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
getDb,
|
2020-01-21 17:36:46 +10:00
|
|
|
initDb,
|
|
|
|
getDbUri
|
2019-06-08 17:49:40 +10:00
|
|
|
};
|