2017-11-01 13:44:54 +00:00
|
|
|
var _ = require('lodash'),
|
2016-09-09 12:23:47 +02:00
|
|
|
config = require('../../config'),
|
|
|
|
utils = require('../../utils');
|
2016-03-20 21:48:15 +00:00
|
|
|
|
|
|
|
function getPaginatedUrl(page, data, absolute) {
|
|
|
|
// If we don't have enough information, return null right away
|
|
|
|
if (!data || !data.relativeUrl || !data.pagination) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2016-11-14 21:38:55 +07:00
|
|
|
var pagePath = utils.url.urlJoin('/', config.get('routeKeywords').page, '/'),
|
2016-03-20 21:48:15 +00:00
|
|
|
// Try to match the base url, as whatever precedes the pagePath
|
2016-09-13 17:41:14 +02:00
|
|
|
baseUrlPattern = new RegExp('(.+)?(/' + config.get('routeKeywords').page + '/\\d+/)'),
|
2016-03-20 21:48:15 +00:00
|
|
|
baseUrlMatch = data.relativeUrl.match(baseUrlPattern),
|
|
|
|
// If there is no match for pagePath, use the original url, without the trailing slash
|
|
|
|
baseUrl = baseUrlMatch ? baseUrlMatch[1] : data.relativeUrl.slice(0, -1),
|
|
|
|
newRelativeUrl;
|
|
|
|
|
|
|
|
if (page === 'next' && data.pagination.next) {
|
2016-11-14 21:38:55 +07:00
|
|
|
newRelativeUrl = utils.url.urlJoin(pagePath, data.pagination.next, '/');
|
2016-03-20 21:48:15 +00:00
|
|
|
} else if (page === 'prev' && data.pagination.prev) {
|
2016-11-14 21:38:55 +07:00
|
|
|
newRelativeUrl = data.pagination.prev > 1 ? utils.url.urlJoin(pagePath, data.pagination.prev, '/') : '/';
|
2016-03-20 21:48:15 +00:00
|
|
|
} else if (_.isNumber(page)) {
|
2016-11-14 21:38:55 +07:00
|
|
|
newRelativeUrl = page > 1 ? utils.url.urlJoin(pagePath, page, '/') : '/';
|
2016-03-20 21:48:15 +00:00
|
|
|
} else {
|
|
|
|
// If none of the cases match, return null right away
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
// baseUrl can be undefined, if there was nothing preceding the pagePath (e.g. first page of the index channel)
|
2016-11-14 21:38:55 +07:00
|
|
|
newRelativeUrl = baseUrl ? utils.url.urlJoin(baseUrl, newRelativeUrl) : newRelativeUrl;
|
2016-03-20 21:48:15 +00:00
|
|
|
|
2017-11-01 13:44:54 +00:00
|
|
|
return utils.url.urlFor({relativeUrl: newRelativeUrl, secure: data.secure}, absolute);
|
2016-03-20 21:48:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = getPaginatedUrl;
|