diff --git a/server.js b/server.js index 7b87ae83e..3bdb77b92 100644 --- a/server.js +++ b/server.js @@ -79,7 +79,6 @@ const config = require('nconf') // DB const DB = require('./server/db.js'); -// FIXME: consider implementing error hanlding for a Promise returned by connect DB.connect(config); //Account Middleware diff --git a/server/db.js b/server/db.js index 7adf3a58f..030d7f61b 100644 --- a/server/db.js +++ b/server/db.js @@ -1,3 +1,10 @@ +// The main purpose of this file is to provide an interface for database +// connection. Even though the code is quite simple and basically a tiny +// wrapper around mongoose package, it works as single point where +// database setup/config is performed and the interface provided here can be +// reused by both the main application and all tests which require database +// connection. + const Mongoose = require('mongoose'); const getMongoDBURL = (config)=>{ @@ -6,29 +13,22 @@ const getMongoDBURL = (config)=>{ 'mongodb://localhost/homebrewery'; }; -const disconnect = ()=>{ - return Mongoose.close(); +const handleConnectionError = (error)=>{ + if(error) { + console.error('Could not connect to a Mongo database: \n'); + console.error(error); + console.error('\nIf you are running locally, make sure mongodb.exe is running and DB URL is configured properly'); + process.exit(1); // non-zero exit code to indicate an error + } }; -const connect = (config)=>{ - const resolver = (resolve, reject)=>{ - Mongoose.connect(getMongoDBURL(config), - { retryWrites: false }, - (error)=>{ - if(error) { - console.error('Could not connect to a Mongo Database.'); - console.log(error); - console.error('If you are running locally, make sure mongodb.exe is running.'); - // FIXME: do we need to pass 'error' to 'reject'? - return reject(); - } +const disconnect = async ()=>{ + return await Mongoose.disconnect(); +}; - return resolve(); - }); - - }; - - return new Promise(resolver); +const connect = async (config)=>{ + return await Mongoose.connect(getMongoDBURL(config), + { retryWrites: false }, handleConnectionError); }; module.exports = {