mirror of
https://github.com/typicode/json-server.git
synced 2025-07-28 12:43:18 +08:00
Merge pull request #27 from manuquentin/add_field_sorting
[RFR] Allows to sort on a field
This commit is contained in:
@ -27,9 +27,13 @@ routes.list = function(req, res, next) {
|
||||
// parameters
|
||||
var _start = req.query._start
|
||||
var _end = req.query._end
|
||||
var _sort = req.query._sort
|
||||
var _sortDir = req.query._sortDir
|
||||
|
||||
delete req.query._start
|
||||
delete req.query._end
|
||||
delete req.query._sort
|
||||
delete req.query._sortDir
|
||||
|
||||
if (req.query.q) {
|
||||
|
||||
@ -68,6 +72,18 @@ routes.list = function(req, res, next) {
|
||||
}
|
||||
}
|
||||
|
||||
if(_sort) {
|
||||
_sortDir = _sortDir || 'ASC'
|
||||
|
||||
array = _.sortBy(array, function(element) {
|
||||
return element[_sort];
|
||||
})
|
||||
|
||||
if (_sortDir === 'DESC') {
|
||||
array.reverse();
|
||||
}
|
||||
}
|
||||
|
||||
// Slice result
|
||||
if (_end) {
|
||||
res.setHeader('X-Total-Count', array.length)
|
||||
|
@ -91,6 +91,32 @@ describe('Server', function() {
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /:resource?sort=', function() {
|
||||
it('should respond with json and sort on a field', function(done) {
|
||||
request(server)
|
||||
.get('/tags?_sort=body')
|
||||
.expect('Content-Type', /json/)
|
||||
.expect([low.db.tags[1], low.db.tags[0], low.db.tags[2]])
|
||||
.expect(200, done)
|
||||
})
|
||||
|
||||
it('should reverse sorting with sortDir=DESC', function(done) {
|
||||
request(server)
|
||||
.get('/tags?_sort=body&_sortDir=DESC')
|
||||
.expect('Content-Type', /json/)
|
||||
.expect([low.db.tags[2], low.db.tags[0], low.db.tags[1]])
|
||||
.expect(200, done)
|
||||
})
|
||||
|
||||
it('should sort on numerical field', function(done) {
|
||||
request(server)
|
||||
.get('/posts?_sort=id&_sortDir=DESC')
|
||||
.expect('Content-Type', /json/)
|
||||
.expect(low.db.posts.reverse())
|
||||
.expect(200, done)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /:resource?_start=&_end=', function() {
|
||||
it('should respond with a sliced array', function(done) {
|
||||
request(server)
|
||||
|
Reference in New Issue
Block a user