Merge pull request #16 from juggy/redis-sort

limit/offset and order clause for redis adapter
This commit is contained in:
1602 2012-01-18 07:52:55 -08:00
commit d05e018234
1 changed files with 53 additions and 8 deletions

View File

@ -80,6 +80,11 @@ BridgeToRedis.prototype.create = function (model, data, callback) {
callback(err, id); callback(err, id);
} }
}); });
// push the id to the list of user ids for sorting
log('SADD s:' + model + ':' + data.id + ' ...');
this.client.sadd("s:" + model, data.id);
}.bind(this)); }.bind(this));
}; };
@ -112,6 +117,8 @@ BridgeToRedis.prototype.destroy = function destroy(model, id, callback) {
this.log('DEL ' + model + ':' + id, t1); this.log('DEL ' + model + ':' + id, t1);
callback(err); callback(err);
}.bind(this)); }.bind(this));
this.log('SREM s:' + model, t1);
this.client.srem("s:" + model, id);
}; };
BridgeToRedis.prototype.possibleIndexes = function (model, filter) { BridgeToRedis.prototype.possibleIndexes = function (model, filter) {
@ -133,15 +140,53 @@ BridgeToRedis.prototype.all = function all(model, filter, callback) {
var log = this.log; var log = this.log;
var t1 = Date.now(); var t1 = Date.now();
var cmd; var cmd;
var that = this;
var sortCmd = [];
var indexes = this.possibleIndexes(model, filter); // ORDER
if (indexes.length) { if (filter && filter.order){
cmd = 'SINTER "' + indexes.join('" "') + '"'; var orders = filter.order;
indexes.push(handleKeys); if (typeof filter.order === "string"){
client.sinter.apply(client, indexes); orders = [filter.order];
} else { }
cmd = 'KEYS ' + model + ':*'; orders.forEach( function (key){
client.keys(model + ':*', handleKeys); sortCmd.push("BY", model + ":*->" + key);
});
}
// LIMIT
if (filter && filter.limit){
var from = (filter.offset || 0), to = from + filter.limit;
sortCmd.push("LIMIT", from, to);
}
// do we need to sort or to query normally
if(sortCmd.length){
sortCmd.unshift("s:" + model);
sortCmd.push("GET", "#");
cmd = "sort " + sortCmd.join(" ");
sortCmd.push(function(err, ids){
console.log( ids);
if (err) {
return callback(err, []);
}
var keys = ids.map(function (i) {
return model + ":" + i;
});
console.log(keys);
handleKeys(err, keys);
});
client.sort.apply(client, sortCmd);
}else{
// Do a normal key lookup with possbible indexes
var indexes = this.possibleIndexes(model, filter);
if (indexes.length) {
cmd = 'SINTER "' + indexes.join('" "') + '"';
indexes.push(handleKeys);
client.sinter.apply(client, indexes, handleKeys);
} else {
cmd = 'KEYS ' + model + ':*';
client.keys(model + ':*', handleKeys);
}
} }
function handleKeys(err, keys) { function handleKeys(err, keys) {