Reverse sort order in redis and memory, test

This commit is contained in:
Anatoliy Chakkaev 2012-03-01 23:57:48 +04:00
parent 0f2d6b527a
commit 9b3d432942
3 changed files with 34 additions and 1 deletions

View File

@ -58,10 +58,17 @@ Memory.prototype.all = function all(model, filter, callback) {
var props = this._models[model].properties;
var allNumeric = true;
var orders = filter.order;
var reverse = false;
if (typeof filter.order === "string") {
orders = [filter.order];
}
orders.forEach(function (key) {
orders.forEach(function (key, i) {
var m = key.match(/\s+(A|DE)SC$/i);
if (m) {
key = key.replace(/\s+(A|DE)SC/i, '');
if (m[1] === 'DE') reverse = true;
}
orders[i] = key;
if (props[key].type.name !== 'Number' && props[key].type.name !== 'Date') {
allNumeric = false;
}
@ -71,6 +78,7 @@ Memory.prototype.all = function all(model, filter, callback) {
} else {
nodes = nodes.sort(literally.bind(orders));
}
if (reverse) nodes = nodes.reverse();
}
}

View File

@ -237,12 +237,18 @@ BridgeToRedis.prototype.all = function all(model, filter, callback) {
function gotKeys(keys) {
// ORDER
var reverse = false;
if (filter && filter.order) {
var orders = filter.order;
if (typeof filter.order === "string"){
orders = [filter.order];
}
orders.forEach(function (key) {
var m = key.match(/\s+(A|DE)SC$/i);
if (m) {
key = key.replace(/\s+DESC/i, '');
if (m[1] === 'DE') reverse = true;
}
if (key !== 'id') {
if (props[key].type.name !== 'Number' && props[key].type.name !== 'Date') {
allNumeric = false;
@ -265,6 +271,10 @@ BridgeToRedis.prototype.all = function all(model, filter, callback) {
sortCmd.push('ALPHA');
}
if (reverse) {
sortCmd.push('DESC');
}
if (sortCmd.length) {
sortCmd.unshift("s:" + model);
sortCmd.push("GET", "#");

View File

@ -472,6 +472,7 @@ function testOrm(schema) {
function done(err, obj) {
if (++i === titles.length) {
doFilterAndSortTest();
doFilterAndSortReverseTest();
doStringTest();
doNumberTest();
}
@ -518,6 +519,20 @@ function testOrm(schema) {
});
}
function doFilterAndSortReverseTest() {
tests += 1;
Post.all({where: {date: isRedis ? 9 : new Date(1000 * 9)}, order: 'title DESC', limit: 3}, function (err, posts) {
if (err) console.log(err);
test.equal(posts.length, 2, 'Exactly 2 posts returned by query');
[ 'Title Z', 'Title C' ].forEach(function (t, i) {
if (posts[i]) {
test.equal(posts[i].title, t);
}
});
finished();
});
}
var fin = 0;
function finished() {
if (++fin === tests) {