1
0
mirror of https://github.com/redis/node-redis.git synced 2025-08-06 02:15:48 +03:00

Add optional callback option to duplicate function

This commit is contained in:
Ruben Bridgewater
2016-04-13 04:00:23 +02:00
parent d2b8f2f391
commit 8e24380d53
3 changed files with 52 additions and 2 deletions

View File

@@ -597,9 +597,10 @@ the second word as first parameter:
client.multi().script('load', 'return 1').exec(...);
client.multi([['script', 'load', 'return 1']]).exec(...);
## client.duplicate([options])
## client.duplicate([options][, callback])
Duplicate all current options and return a new redisClient instance. All options passed to the duplicate function are going to replace the original option.
If you pass a callback, duplicate is going to wait until the client is ready and returns it in the callback. If an error occurs in the meanwhile, that is going to return an error instead in the callback.
## client.send_command(command_name[, [args][, callback]])

View File

@@ -79,7 +79,11 @@ RedisClient.prototype.unref = function () {
}
};
RedisClient.prototype.duplicate = function (options) {
RedisClient.prototype.duplicate = function (options, callback) {
if (typeof options === 'function') {
callback = options;
options = null;
}
var existing_options = utils.clone(this.options);
options = utils.clone(options);
for (var elem in options) { // jshint ignore: line
@@ -87,5 +91,18 @@ RedisClient.prototype.duplicate = function (options) {
}
var client = new RedisClient(existing_options);
client.selected_db = this.selected_db;
if (typeof callback === 'function') {
var ready_listener = function () {
callback(null, client);
client.removeAllListeners(error_listener);
};
var error_listener = function (err) {
callback(err);
client.end(true);
};
client.once('ready', ready_listener);
client.once('error', error_listener);
return;
}
return client;
};

View File

@@ -66,6 +66,38 @@ describe('The node_redis client', function () {
done();
});
});
it('works with a callback', function (done) {
client.duplicate(function (err, client) {
assert(!err);
assert.strictEqual(client.ready, true);
client.quit(done);
});
});
it('works with a callback and errors out', function (done) {
client.duplicate({
port: '9999'
}, function (err, client) {
assert.strictEqual(err.code, 'ECONNREFUSED');
done(client);
});
});
it('works with a promises', function () {
return client.duplicateAsync().then(function (client) {
assert.strictEqual(client.ready, true);
return client.quitAsync();
});
});
it('works with a promises and errors', function () {
return client.duplicateAsync({
port: 9999
}).catch(function (err) {
assert.strictEqual(err.code, 'ECONNREFUSED');
});
});
});
describe('big data', function () {