From 47f0731df603ed9bbb6e288e1089404427742f9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lien=20Georget?= Date: Mon, 7 Mar 2016 18:34:27 +0100 Subject: [PATCH] Improve JSON API pagination --- .../hooks/jsonapi/helpers/response.js | 28 ++++++++++++++----- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/lib/configuration/hooks/jsonapi/helpers/response.js b/lib/configuration/hooks/jsonapi/helpers/response.js index 6fc59f4a05..17c0f374f7 100644 --- a/lib/configuration/hooks/jsonapi/helpers/response.js +++ b/lib/configuration/hooks/jsonapi/helpers/response.js @@ -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':