2020-04-29 18:44:27 +03:00
|
|
|
const _ = require('lodash');
|
2020-05-28 13:57:02 +03:00
|
|
|
const urlUtils = require('../../shared/url-utils');
|
2016-03-21 00:48:15 +03: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;
|
|
|
|
}
|
2020-04-29 18:44:27 +03:00
|
|
|
|
|
|
|
// routeKeywords.page: 'page'
|
|
|
|
const pagePath = urlUtils.urlJoin('/page/');
|
|
|
|
|
|
|
|
// Try to match the base url, as whatever precedes the pagePath
|
2018-04-17 12:36:05 +03:00
|
|
|
// routeKeywords.page: 'page'
|
2020-04-29 18:44:27 +03:00
|
|
|
const baseUrlPattern = new RegExp('(.+)?(/page/\\d+/)');
|
|
|
|
|
|
|
|
const baseUrlMatch = data.relativeUrl.match(baseUrlPattern);
|
|
|
|
|
|
|
|
// If there is no match for pagePath, use the original url, without the trailing slash
|
|
|
|
const baseUrl = baseUrlMatch ? baseUrlMatch[1] : data.relativeUrl.slice(0, -1);
|
|
|
|
|
|
|
|
let newRelativeUrl;
|
2016-03-21 00:48:15 +03:00
|
|
|
|
|
|
|
if (page === 'next' && data.pagination.next) {
|
2019-06-18 16:13:55 +03:00
|
|
|
newRelativeUrl = urlUtils.urlJoin(pagePath, data.pagination.next, '/');
|
2016-03-21 00:48:15 +03:00
|
|
|
} else if (page === 'prev' && data.pagination.prev) {
|
2019-06-18 16:13:55 +03:00
|
|
|
newRelativeUrl = data.pagination.prev > 1 ? urlUtils.urlJoin(pagePath, data.pagination.prev, '/') : '/';
|
2016-03-21 00:48:15 +03:00
|
|
|
} else if (_.isNumber(page)) {
|
2019-06-18 16:13:55 +03:00
|
|
|
newRelativeUrl = page > 1 ? urlUtils.urlJoin(pagePath, page, '/') : '/';
|
2016-03-21 00:48:15 +03: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)
|
2019-06-18 16:13:55 +03:00
|
|
|
newRelativeUrl = baseUrl ? urlUtils.urlJoin(baseUrl, newRelativeUrl) : newRelativeUrl;
|
2016-03-21 00:48:15 +03:00
|
|
|
|
2019-06-18 16:13:55 +03:00
|
|
|
return urlUtils.urlFor({relativeUrl: newRelativeUrl, secure: data.secure}, absolute);
|
2016-03-21 00:48:15 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = getPaginatedUrl;
|