Last active
August 29, 2015 14:00
-
-
Save lordfriend/36fddf9d477199d6e673 to your computer and use it in GitHub Desktop.
Wrap redis client using kriskowal/q promise
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
/** | |
* 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