From d7555bfb64bf1923a4c65cb6d86d301618aa6ded Mon Sep 17 00:00:00 2001 From: Fabien Franzen Date: Wed, 13 Aug 2014 16:24:11 +0200 Subject: [PATCH] Allow runtime override of scope/relation order query param --- lib/scope.js | 6 +++--- test/scope.test.js | 54 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 3 deletions(-) diff --git a/lib/scope.js b/lib/scope.js index 0c5ea86c..dd0fe194 100644 --- a/lib/scope.js +++ b/lib/scope.js @@ -277,11 +277,11 @@ function mergeQuery(base, update) { base.collect = update.collect; } - // overwrite order - if (update.order) { + // set order + if (!base.order && update.order) { base.order = update.order; } - + // overwrite pagination if (update.limit !== undefined) { base.limit = update.limit; diff --git a/test/scope.test.js b/test/scope.test.js index 2060c80e..c8033c82 100644 --- a/test/scope.test.js +++ b/test/scope.test.js @@ -76,3 +76,57 @@ describe('scope', function () { }); }); }); + +describe('scope - order', function () { + + before(function () { + db = getSchema(); + Station = db.define('Station', { + name: {type: String, index: true}, + order: {type: Number, index: true} + }); + Station.scope('reverse', {order: 'order DESC'}); + }); + + beforeEach(function (done) { + Station.destroyAll(done); + }); + + beforeEach(function (done) { + Station.create({ name: 'a', order: 1 }, done); + }); + + beforeEach(function (done) { + Station.create({ name: 'b', order: 2 }, done); + }); + + beforeEach(function (done) { + Station.create({ name: 'c', order: 3 }, done); + }); + + it('should define scope with default order', function (done) { + Station.reverse(function(err, stations) { + stations[0].name.should.equal('c'); + stations[0].order.should.equal(3); + stations[1].name.should.equal('b'); + stations[1].order.should.equal(2); + stations[2].name.should.equal('a'); + stations[2].order.should.equal(1); + done(); + }); + }); + + it('should override default scope order', function (done) { + Station.reverse({order: 'order ASC'}, function(err, stations) { + stations[0].name.should.equal('a'); + stations[0].order.should.equal(1); + stations[1].name.should.equal('b'); + stations[1].order.should.equal(2); + stations[2].name.should.equal('c'); + stations[2].order.should.equal(3); + done(); + }); + }); + +}); +