mirror of
https://github.com/typicode/json-server.git
synced 2025-07-28 20:52:08 +08:00
Add basic pagination
This commit is contained in:
@ -47,6 +47,7 @@ module.exports = function (db, name) {
|
||||
var q = req.query.q
|
||||
var _start = req.query._start
|
||||
var _end = req.query._end
|
||||
var _page = req.query._page
|
||||
var _sort = req.query._sort
|
||||
var _order = req.query._order
|
||||
var _limit = req.query._limit
|
||||
@ -146,17 +147,23 @@ module.exports = function (db, name) {
|
||||
}
|
||||
|
||||
// Slice result
|
||||
if (_end || _limit) {
|
||||
if (_end || _limit || _page) {
|
||||
res.setHeader('X-Total-Count', chain.size())
|
||||
res.setHeader('Access-Control-Expose-Headers', 'X-Total-Count')
|
||||
}
|
||||
|
||||
if (_page) {
|
||||
_page = parseInt(_page, 10)
|
||||
_page = _page >= 1 ? _page : 1
|
||||
_limit = parseInt(_limit, 10) || 10
|
||||
_start = (_page - 1) * _limit
|
||||
chain = chain.slice(_start, _start + _limit)
|
||||
} else if (_end) {
|
||||
_start = parseInt(_start, 10) || 0
|
||||
|
||||
if (_end) {
|
||||
_end = parseInt(_end, 10)
|
||||
chain = chain.slice(_start, _end)
|
||||
} else if (_limit) {
|
||||
_start = parseInt(_start, 10) || 0
|
||||
_limit = parseInt(_limit, 10)
|
||||
chain = chain.slice(_start, _start + _limit)
|
||||
}
|
||||
|
@ -51,6 +51,24 @@ describe('Server', function () {
|
||||
{resource: {name: 'howe'}}
|
||||
]
|
||||
|
||||
db.list = [
|
||||
{id: 1},
|
||||
{id: 2},
|
||||
{id: 3},
|
||||
{id: 4},
|
||||
{id: 5},
|
||||
{id: 6},
|
||||
{id: 7},
|
||||
{id: 8},
|
||||
{id: 9},
|
||||
{id: 10},
|
||||
{id: 11},
|
||||
{id: 12},
|
||||
{id: 13},
|
||||
{id: 14},
|
||||
{id: 15}
|
||||
]
|
||||
|
||||
server = jsonServer.create()
|
||||
router = jsonServer.router(db)
|
||||
server.use(jsonServer.defaults())
|
||||
@ -236,6 +254,30 @@ describe('Server', function () {
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /:resource?_page=', function () {
|
||||
it('should paginate', function (done) {
|
||||
request(server)
|
||||
.get('/list?_page=2')
|
||||
.expect('Content-Type', /json/)
|
||||
.expect('x-total-count', db.list.length.toString())
|
||||
.expect('Access-Control-Expose-Headers', 'X-Total-Count')
|
||||
.expect(db.list.slice(10, 20))
|
||||
.expect(200, done)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /:resource?_page=&_limit=', function () {
|
||||
it('should paginate with a custom limit', function (done) {
|
||||
request(server)
|
||||
.get('/list?_page=2&_limit=1')
|
||||
.expect('Content-Type', /json/)
|
||||
.expect('x-total-count', db.list.length.toString())
|
||||
.expect('Access-Control-Expose-Headers', 'X-Total-Count')
|
||||
.expect(db.list.slice(1, 2))
|
||||
.expect(200, done)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /:resource?attr_gte=&attr_lte=', function () {
|
||||
it('should respond with a limited array', function (done) {
|
||||
request(server)
|
||||
|
Reference in New Issue
Block a user