Last active
August 29, 2015 14:06
-
-
Save totherik/94db23e9d90a5ffc0ee2 to your computer and use it in GitHub Desktop.
Resilient MongoDb Connection using Promises and Levee
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var DbConn = require('./conn'); | |
var Levee = require('levee'); | |
module.exports = function (options) { | |
var conn, breaker; | |
conn = new DbConn(options.uri); | |
breaker = Levee.createBreaker(conn, { maxFailures: 1, resetTimeout: 5000 }); | |
return function db(req, res, next) { | |
breaker.run(null, function (err, db) { | |
req.db = db; | |
next(err); | |
}); | |
}; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
var Promise = require('promise'); | |
var Mongo = require('mongodb'); | |
function Connection(uri) { | |
this.uri = uri || Mongo.Db.DEFAULT_URL; | |
this.promise = undefined; | |
this.connect(); | |
} | |
Connection.prototype.connect = function connect() { | |
var self, uri; | |
self = this; | |
uri = this.uri; | |
this.promise = new Promise(function (resolve, reject) { | |
Mongo.Db.connect(uri, { server: { auto_reconnect: true } }, function (err, db) { | |
if (err) { | |
reject(err); | |
return; | |
} | |
db.on('close', function (server, db) { | |
self.promise = Promise.reject(new Error('mongodb server disconnected.')); | |
server.once('reconnect', function () { | |
self.promise = Promise.resolve(db); | |
}); | |
}); | |
resolve(db); | |
}); | |
}); | |
}; | |
Connection.prototype.execute = function execute(_, callback) { | |
var self = this; | |
this.promise.then(function (db) { | |
callback(null, db); | |
}, function (err) { | |
self.connect(); | |
callback(err); | |
}); | |
}; | |
module.exports = Connection; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment