mirror of
https://github.com/naturalcrit/homebrewery.git
synced 2025-12-24 18:32:41 +00:00
Merge pull request #1931 from AlexeySachkov/private/asachkov/outline-db-connection
[NFC] Outline database connection into a separate file
This commit is contained in:
13
server.js
13
server.js
@@ -77,16 +77,9 @@ const config = require('nconf')
|
||||
.file('environment', { file: `config/${process.env.NODE_ENV}.json` })
|
||||
.file('defaults', { file: 'config/default.json' });
|
||||
|
||||
//DB
|
||||
const mongoose = require('mongoose');
|
||||
mongoose.connect(config.get('mongodb_uri') || config.get('mongolab_uri') || 'mongodb://localhost/naturalcrit',
|
||||
{ retryWrites: false });
|
||||
mongoose.connection.on('error', (err)=>{
|
||||
console.log('Error : Could not connect to a Mongo Database.');
|
||||
console.log(' If you are running locally, make sure mongodb.exe is running.');
|
||||
console.log(err);
|
||||
throw 'Can not connect to Mongo';
|
||||
});
|
||||
// DB
|
||||
const DB = require('./server/db.js');
|
||||
DB.connect(config);
|
||||
|
||||
//Account Middleware
|
||||
app.use((req, res, next)=>{
|
||||
|
||||
37
server/db.js
Normal file
37
server/db.js
Normal file
@@ -0,0 +1,37 @@
|
||||
// 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)=>{
|
||||
return config.get('mongodb_uri') ||
|
||||
config.get('mongolab_uri') ||
|
||||
'mongodb://localhost/homebrewery';
|
||||
};
|
||||
|
||||
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 disconnect = async ()=>{
|
||||
return await Mongoose.disconnect();
|
||||
};
|
||||
|
||||
const connect = async (config)=>{
|
||||
return await Mongoose.connect(getMongoDBURL(config),
|
||||
{ retryWrites: false }, handleConnectionError);
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
connect : connect,
|
||||
disconnect : disconnect
|
||||
};
|
||||
Reference in New Issue
Block a user