Skip to content

Commit

Permalink
Added functionality for restore connection with database
Browse files Browse the repository at this point in the history
  • Loading branch information
AKosmachyov committed May 30, 2017
1 parent b72c70b commit 9cc62ea
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 5 deletions.
3 changes: 2 additions & 1 deletion server/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,9 @@ app.use(function(err, req, res, next) {
if (err.name == "MongoError") {
err.message = "Problem with database";
err.status = 500;
dataBase.reconnectToDB();
}
res.send(err.message, err.status || 500);
res.status(err.status || 500).send(err.message);
});

module.exports = app;
41 changes: 37 additions & 4 deletions server/database.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ const HttpError = require('./error/HttpError');

const url = 'mongodb://localhost:27017/news-portal';

var tempFlag = false;

class DataBase {
constructor() {
MongoClient.connect(url, {reconnectTries: 5}, (err, db) => {
if(err)
throw new Error("Can't connect to the database");
console.log("Connected successfully to db");
module.exports = db;
if (err)
throw new Error('Can not connect to the database');
console.log('Connected successfully to db');
this.usersCollection = db.collection('Users');
this.newsCollection = db.collection('News');
this.tokensCollection = db.collection('Tokens');
Expand Down Expand Up @@ -125,6 +126,38 @@ class DataBase {
})
})
}

connectToDb(self) {
MongoClient.connect(url, {reconnectTries: 5}, (err, db) => {
if (err) {
console.log("Can not connect to the database");
tempFlag = false;
return self.reconnectToDB();
}
console.log("Connected successfully to db");
self.setCollectionToClass({
usersCollection: db.collection('Users'),
newsCollection: db.collection('News'),
tokensCollection: db.collection('Tokens')
});
tempFlag = false;
});

}

reconnectToDB() {
if(tempFlag)
return;
tempFlag = true;
const _self = this;
setTimeout(_self.connectToDb, 5000, _self);
}

setCollectionToClass(obj) {
this.usersCollection = obj.usersCollection;
this.newsCollection = obj.newsCollection;
this.tokensCollection = obj.tokensCollection;
}
}

module.exports = new DataBase();

0 comments on commit 9cc62ea

Please sign in to comment.