0
Fork 0
mirror of https://github.com/TryGhost/Ghost.git synced 2025-01-27 22:49:56 -05:00
ghost/core/server/models/base/utils.js
Hannah Wolfe 16f98ee80b Move pagination formatting into a util
refs #2896

- moves repeated code out of models
- creates a new file for unit-testable code (this should be moved in future)
- adds a default for `page` as that seems sensible
- adds 100% test coverage for the new file
2015-06-15 16:46:42 +01:00

36 lines
1.1 KiB
JavaScript

/**
* # Utils
* Parts of the model code which can be split out and unit tested
*/
/**
* Takes the number of items returned and original options and calculates all of the pagination meta data
* TODO: Could be moved to either middleware or a bookshelf plugin?
* @param {Number} totalItems
* @param {Object} options
* @returns {Object} pagination
*/
module.exports.paginateResponse = function paginateResponse(totalItems, options) {
var calcPages = Math.ceil(totalItems / options.limit) || 0,
pagination = {};
pagination.page = options.page || 1;
pagination.limit = options.limit;
pagination.pages = calcPages === 0 ? 1 : calcPages;
pagination.total = totalItems;
pagination.next = null;
pagination.prev = null;
if (pagination.pages > 1) {
if (pagination.page === 1) {
pagination.next = pagination.page + 1;
} else if (pagination.page === pagination.pages) {
pagination.prev = pagination.page - 1;
} else {
pagination.next = pagination.page + 1;
pagination.prev = pagination.page - 1;
}
}
return pagination;
};