mirror of
https://github.com/naturalcrit/homebrewery.git
synced 2026-01-07 22:52:39 +00:00
[NFC] Outline database connection into a separate file
This commit is contained in:
14
server.js
14
server.js
@@ -77,16 +77,10 @@ const config = require('nconf')
|
|||||||
.file('environment', { file: `config/${process.env.NODE_ENV}.json` })
|
.file('environment', { file: `config/${process.env.NODE_ENV}.json` })
|
||||||
.file('defaults', { file: 'config/default.json' });
|
.file('defaults', { file: 'config/default.json' });
|
||||||
|
|
||||||
//DB
|
// DB
|
||||||
const mongoose = require('mongoose');
|
const DB = require('./server/db.js');
|
||||||
mongoose.connect(config.get('mongodb_uri') || config.get('mongolab_uri') || 'mongodb://localhost/naturalcrit',
|
// FIXME: consider implementing error hanlding for a Promise returned by connect
|
||||||
{ retryWrites: false });
|
DB.connect(config);
|
||||||
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';
|
|
||||||
});
|
|
||||||
|
|
||||||
//Account Middleware
|
//Account Middleware
|
||||||
app.use((req, res, next)=>{
|
app.use((req, res, next)=>{
|
||||||
|
|||||||
37
server/db.js
Normal file
37
server/db.js
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
const Mongoose = require('mongoose');
|
||||||
|
|
||||||
|
const getMongoDBURL = (config)=>{
|
||||||
|
return config.get('mongodb_uri') ||
|
||||||
|
config.get('mongolab_uri') ||
|
||||||
|
'mongodb://localhost/homebrewery';
|
||||||
|
};
|
||||||
|
|
||||||
|
const disconnect = ()=>{
|
||||||
|
return Mongoose.close();
|
||||||
|
};
|
||||||
|
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
|
return resolve();
|
||||||
|
});
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
return new Promise(resolver);
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
connect : connect,
|
||||||
|
disconnect : disconnect
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user