Skip to content

Instantly share code, notes, and snippets.

@lordfriend
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lordfriend/36fddf9d477199d6e673 to your computer and use it in GitHub Desktop.
Save lordfriend/36fddf9d477199d6e673 to your computer and use it in GitHub Desktop.
Wrap redis client using kriskowal/q promise
/**
* Wrap redis client using kriskowal/q promise
*/
var redis = require('redis');
var redisClient = redis.createClient();
var Multi = redis.Multi;
var Q = require('q');
var _ = require('underscore');
var object = function(o) {
function F(){}
F.prototype = o;
return new F();
};
var miscellaneous = function(subType, superType) {
var prototype = object(superType.prototype);
prototype.constructor = subType;
subType.prototype = prototype;
};
var commands = require('redis/lib/commands');
function RedisQ() {
//do nothing
}
RedisQ.prototype.sendCommand = function(command, args, callback) {
var deferred = Q.defer();
redisClient.send_command.call(redisClient, command, args, function(err, replies) {
if(err) {
deferred.reject(err);
} else {
deferred.resolve(replies);
}
});
return deferred.promise.nodeify(callback);
};
_.each(commands, function(command) {
RedisQ.prototype[command] = function(args, callback) {
if(_.isArray(args) && _.isFunction(callback)) {
return this.sendCommand(command, args, callback);
} else if(_.isArray(args))
return this.sendCommand(command, args);
} else {
// arguments is separate arguments
if(!_.isFunction(arguments[arguments.length - 1])){
return this.sendCommand(command, _.toArray(arguments));
} else {
var argumentsArray = _.toArray(arguments);
var lastArg = argumentsArray.pop();
return this.sendCommand(command, argumentsArray, lastArg);
}
}
};
});
exports.client = function() {
return new RedisQ();
};
function MultiQ(args) {
Multi.call(this, redisClient, args);
}
miscellaneous.inheritPrototype(MultiQ, Multi);
var superExec = MultiQ.prototype.exec;
MultiQ.prototype.exec = function(callback) {
var deferred = Q.defer();
superExec.call(this, function(err, replies){
if(err) {
deferred.reject(err);
} else {
deferred.resolve(replies);
}
});
return deferred.promise.nodeify(callback);
};
RedisQ.prototype.multi = function(args) {
return new MultiQ(redisClient, args);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment