I wrote connection logic for a wrapper around RethinkDB in node.js. While it works, I know it can be cleaned up, and done in a better manner. Essentially the logic is start at the first host in config.hosts
, if _connect()
fails, then try the next host in the array. This continues for three times, or until config.hosts
is empty. If __connect()
is successful just set rethinkdbConnection
to the returned connection object.
var config.hosts = ['10.0.0.1', '10.0.0.2', '10.0.0.3'];
var rethinkdbConnection;
exports.connect = function(config, callback) {
var rethinkdbConfig = clone(config);
delete rethinkdbConfig.hosts;
function _connect(callback) {
rethinkdbConfig.host = config.hosts.shift();
r.connect(rethinkdbConfig, function(error, connection) {
if(error) {
return callback(error);
}
return callback(null, connection);
});
}
_connect(function(error, connection) {
if(error) {
if(!config.hosts.length) {
return callback(error);
}
_connect(function(error, connection) {
if(error) {
if(!config.hosts.length) {
return callback(error);
}
_connect(function(error, connection) {
if(error) {
return callback(error);
}
});
}
});
} else {
rethinkdbConnection = connection;
return callback();
}
});
};
What is a better way to write this?
Also it would be great instead of arbitrarily trying _connet()
3 times, to try as many times as the length of config.hosts
instead.