Improve JSON API pagination

This commit is contained in:
Aurélien Georget 2016-03-07 18:34:27 +01:00
parent 6221cd48bc
commit 47f0731df6

View File

@ -46,7 +46,7 @@ module.exports = {
// Fetch and format value
const value = this.fetchValue(ctx, object);
if (!_.isEmpty(value)) {
if (!_.isNull(value)) {
ctx.response.body = yield this.serialize(ctx, type, object, value, matchedRoute);
}
},
@ -160,7 +160,7 @@ module.exports = {
// Get current page number
const value = _.first(_.values(_.pick(ctx.state.query, 'page[number]')));
const currentPage = _.isEmpty(value) ? 1 : value;
const currentPage = _.isEmpty(value) || parseInt(value, 10) === 0 ? 1 : value;
// Verify integer
if (currentPage.toString() === parseInt(currentPage, 10).toString()) {
@ -169,17 +169,31 @@ module.exports = {
links.next = ctx.request.origin + ctx.state.url + '?page[number]=' + (parseInt(currentPage, 10) + 1);
links.last = ctx.request.origin + ctx.state.url + '?page[number]=' + pageNumber;
// Second page
if ((parseInt(currentPage, 10) - 1) === 0) {
links.prev = links.first;
}
// Before last page
if ((parseInt(currentPage, 10) - 1) === pageNumber) {
links.next = links.last;
}
// No data
if (pageNumber === 0) {
links.prev = null;
links.next = null;
links.last = null;
}
// Last page
if (ctx.request.url === ctx.state.url + '?page[number]=' + pageNumber) {
// Don't display useless
if (parseInt(currentPage, 10) === pageNumber) {
links.last = null;
links.next = null;
} else if (ctx.request.url === ctx.state.url) {
// First page
}
// First page
if (parseInt(currentPage, 10) === 1) {
links.first = null;
links.prev = null;
}
@ -295,7 +309,7 @@ module.exports = {
*/
fetchValue: function (ctx, object) {
const data = ctx.body.toJSON() || ctx.body;
const data = _.isFunction(_.get(ctx.body, 'toJSON')) ? ctx.body.toJSON() : ctx.body;
switch (object) {
case 'collection':