From 36465387454cdb797f886f732d40a70faa92cbad Mon Sep 17 00:00:00 2001 From: eug-vs Date: Sat, 14 Nov 2020 16:31:59 +0300 Subject: refactor: reuse Mongoose connection in Agenda --- src/connectDb.js | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/connectDb.js (limited to 'src/connectDb.js') diff --git a/src/connectDb.js b/src/connectDb.js new file mode 100644 index 0000000..c7ad13b --- /dev/null +++ b/src/connectDb.js @@ -0,0 +1,40 @@ +const mongoose = require('mongoose'); +const Promise = require('bluebird'); + +const MONGODB_URL = process.env.MONGODB_URI || 'mongodb://localhost:27017/bsu-fantom'; +const { MONGODB_USER, MONGODB_PASSWORD } = process.env; + +let connection; + +const connectDb = () => new Promise ((resolve, reject) => { + mongoose.Promise = Promise; + + mongoose.connect(MONGODB_URL, { + user: MONGODB_USER, + pass: MONGODB_PASSWORD, + useNewUrlParser: true, + useUnifiedTopology: true, + useCreateIndex: true, + useFindAndModify: false, + family: 4 // Use IPv4, skip trying IPv6 + }); + + connection = mongoose.connection; + + connection.on('error', error => { + console.log(error); + reject(error); + }); + + connection.once('open', () => { + console.log('Connection to MongoDB successfull') + resolve(); + }); +}); + +const getConnection = () => connection; + +module.exports = { + connectDb, + getConnection +}; -- cgit v1.2.3