Refactor the pagination data retrieval

master
Mark Moffat 2020-03-19 17:02:22 +10:30
parent 4b3867e47f
commit 5f81173919
5 changed files with 68 additions and 53 deletions

View File

@ -616,33 +616,45 @@ const newId = () => {
return new ObjectId(); return new ObjectId();
}; };
const getData = (req, page, query) => { /**
* @param {boolean} frontend // whether or not this is an front or admin call
* @param {req} req // express `req` object
* @param {integer} page // The page number
* @param {string} collection // The collection to search
* @param {object} query // The mongo query
* @param {object} sort // The mongo sort
*/
const paginateData = (frontend, req, page, collection, query, sort) => {
const db = req.app.db; const db = req.app.db;
const config = getConfig(); const config = getConfig();
const numberProducts = config.productsPerPage ? config.productsPerPage : 6; let numberItems = 10;
if(frontend){
numberItems = config.productsPerPage ? config.productsPerPage : 6;
}
let skip = 0; let skip = 0;
if(page > 1){ if(page > 1){
skip = (page - 1) * numberProducts; skip = (page - 1) * numberItems;
} }
if(!query){ if(!query){
query = {}; query = {};
} }
if(!sort){
query.productPublished = { $ne: false }; sort = {};
}
// Run our queries // Run our queries
return Promise.all([ return Promise.all([
db.products.find(query).skip(skip).limit(parseInt(numberProducts)).toArray(), db[collection].find(query).skip(skip).limit(parseInt(numberItems)).sort(sort).toArray(),
db.products.countDocuments(query) db[collection].countDocuments(query)
]) ])
.then((result) => { .then((result) => {
const returnData = { data: result[0], totalProducts: result[1] }; const returnData = { data: result[0], totalItems: result[1] };
return returnData; return returnData;
}) })
.catch((err) => { .catch((err) => {
throw new Error('Error retrieving products'); throw new Error('Error retrieving paginated data');
}); });
}; };
@ -702,7 +714,7 @@ module.exports = {
sendEmail, sendEmail,
getId, getId,
newId, newId,
getData, paginateData,
hooker, hooker,
getCountryList, getCountryList,
cleanAmount cleanAmount

View File

@ -80,8 +80,8 @@ $(document).ready(function (){
if($('#pager').length){ if($('#pager').length){
var pageNum = $('#pageNum').val(); var pageNum = $('#pageNum').val();
var pageLen = $('#productsPerPage').val(); var pageLen = $('#itemsPerPage').val();
var productCount = $('#totalProductCount').val(); var itemCount = $('#totalItemCount').val();
var paginateUrl = $('#paginateUrl').val(); var paginateUrl = $('#paginateUrl').val();
var searchTerm = $('#searchTerm').val(); var searchTerm = $('#searchTerm').val();
@ -90,11 +90,12 @@ $(document).ready(function (){
} }
var pagerHref = '/' + paginateUrl + '/' + searchTerm + '{{number}}'; var pagerHref = '/' + paginateUrl + '/' + searchTerm + '{{number}}';
var totalProducts = Math.ceil(productCount / pageLen); var totalItems = Math.ceil(itemCount / pageLen);
if(parseInt(productCount) > parseInt(pageLen)){ if(parseInt(itemCount) > parseInt(pageLen)){
console.log('here?');
$('#pager').bootpag({ $('#pager').bootpag({
total: totalProducts, total: totalItems,
page: pageNum, page: pageNum,
maxVisible: 5, maxVisible: 5,
href: pagerHref, href: pagerHref,

File diff suppressed because one or more lines are too long

View File

@ -16,7 +16,7 @@ const {
updateTotalCart, updateTotalCart,
emptyCart, emptyCart,
updateSubscriptionCheck, updateSubscriptionCheck,
getData, paginateData,
addSitemapProducts, addSitemapProducts,
getCountryList getCountryList
} = require('../lib/common'); } = require('../lib/common');
@ -642,38 +642,38 @@ router.get('/search/:searchTerm/:pageNum?', (req, res) => {
} }
Promise.all([ Promise.all([
getData(req, pageNum, { _id: { $in: lunrIdArray } }), paginateData(true, req, pageNum, 'products', { _id: { $in: lunrIdArray } }),
getMenu(db) getMenu(db)
]) ])
.then(([results, menu]) => { .then(([results, menu]) => {
// If JSON query param return json instead // If JSON query param return json instead
if(req.query.json === 'true'){ if(req.query.json === 'true'){
res.status(200).json(results.data); res.status(200).json(results.data);
return; return;
} }
res.render(`${config.themeViews}index`, { res.render(`${config.themeViews}index`, {
title: 'Results', title: 'Results',
results: results.data, results: results.data,
filtered: true, filtered: true,
session: req.session, session: req.session,
metaDescription: req.app.config.cartTitle + ' - Search term: ' + searchTerm, metaDescription: req.app.config.cartTitle + ' - Search term: ' + searchTerm,
searchTerm: searchTerm, searchTerm: searchTerm,
message: clearSessionValue(req.session, 'message'), message: clearSessionValue(req.session, 'message'),
messageType: clearSessionValue(req.session, 'messageType'), messageType: clearSessionValue(req.session, 'messageType'),
productsPerPage: numberProducts, productsPerPage: numberProducts,
totalProductCount: results.totalProducts, totalProductCount: results.totalItems,
pageNum: pageNum, pageNum: pageNum,
paginateUrl: 'search', paginateUrl: 'search',
config: config, config: config,
menu: sortMenu(menu), menu: sortMenu(menu),
helpers: req.handlebars.helpers, helpers: req.handlebars.helpers,
showFooter: 'showFooter' showFooter: 'showFooter'
});
})
.catch((err) => {
console.error(colors.red('Error searching for products', err));
}); });
})
.catch((err) => {
console.error(colors.red('Error searching for products', err));
});
}); });
// search products // search products
@ -695,7 +695,7 @@ router.get('/category/:cat/:pageNum?', (req, res) => {
} }
Promise.all([ Promise.all([
getData(req, pageNum, { _id: { $in: lunrIdArray } }), paginateData(true, req, pageNum, 'products', { _id: { $in: lunrIdArray } }),
getMenu(db) getMenu(db)
]) ])
.then(([results, menu]) => { .then(([results, menu]) => {
@ -717,7 +717,7 @@ router.get('/category/:cat/:pageNum?', (req, res) => {
message: clearSessionValue(req.session, 'message'), message: clearSessionValue(req.session, 'message'),
messageType: clearSessionValue(req.session, 'messageType'), messageType: clearSessionValue(req.session, 'messageType'),
productsPerPage: numberProducts, productsPerPage: numberProducts,
totalProductCount: results.totalProducts, totalProductCount: results.totalItems,
pageNum: pageNum, pageNum: pageNum,
menuLink: _.find(sortedMenu.items, (obj) => { return obj.link === searchTerm; }), menuLink: _.find(sortedMenu.items, (obj) => { return obj.link === searchTerm; }),
paginateUrl: 'category', paginateUrl: 'category',
@ -777,7 +777,7 @@ router.get('/page/:pageNum', (req, res, next) => {
const numberProducts = config.productsPerPage ? config.productsPerPage : 6; const numberProducts = config.productsPerPage ? config.productsPerPage : 6;
Promise.all([ Promise.all([
getData(req, req.params.pageNum), paginateData(true, req, req.params.pageNum, 'products'),
getMenu(db) getMenu(db)
]) ])
.then(([results, menu]) => { .then(([results, menu]) => {
@ -796,7 +796,7 @@ router.get('/page/:pageNum', (req, res, next) => {
metaDescription: req.app.config.cartTitle + ' - Products page: ' + req.params.pageNum, metaDescription: req.app.config.cartTitle + ' - Products page: ' + req.params.pageNum,
config: req.app.config, config: req.app.config,
productsPerPage: numberProducts, productsPerPage: numberProducts,
totalProductCount: results.totalProducts, totalProductCount: results.totalItems,
pageNum: req.params.pageNum, pageNum: req.params.pageNum,
paginateUrl: 'page', paginateUrl: 'page',
helpers: req.handlebars.helpers, helpers: req.handlebars.helpers,
@ -818,7 +818,7 @@ router.get('/:page?', async (req, res, next) => {
// if no page is specified, just render page 1 of the cart // if no page is specified, just render page 1 of the cart
if(!req.params.page){ if(!req.params.page){
Promise.all([ Promise.all([
getData(req, 1, {}), paginateData(true, req, 1, 'products', {}),
getMenu(db) getMenu(db)
]) ])
.then(([results, menu]) => { .then(([results, menu]) => {
@ -828,6 +828,8 @@ router.get('/:page?', async (req, res, next) => {
return; return;
} }
console.log('results', results);
res.render(`${config.themeViews}index`, { res.render(`${config.themeViews}index`, {
title: `${config.cartTitle} - Shop`, title: `${config.cartTitle} - Shop`,
theme: config.theme, theme: config.theme,
@ -837,7 +839,7 @@ router.get('/:page?', async (req, res, next) => {
messageType: clearSessionValue(req.session, 'messageType'), messageType: clearSessionValue(req.session, 'messageType'),
config, config,
productsPerPage: numberProducts, productsPerPage: numberProducts,
totalProductCount: results.totalProducts, totalProductCount: results.totalItems,
pageNum: 1, pageNum: 1,
paginateUrl: 'page', paginateUrl: 'page',
helpers: req.handlebars.helpers, helpers: req.handlebars.helpers,

View File

@ -58,9 +58,9 @@
{{/each}} {{/each}}
</div> </div>
</div> </div>
<input type="hidden" id="productsPerPage" value="{{productsPerPage}}" > <input type="hidden" id="itemsPerPage" value="{{productsPerPage}}" >
<input type="hidden" id="pageNum" value="{{pageNum}}"> <input type="hidden" id="pageNum" value="{{pageNum}}">
<input type="hidden" id="totalProductCount" value="{{totalProductCount}}"> <input type="hidden" id="totalItemCount" value="{{totalProductCount}}">
<input type="hidden" id="paginateUrl" value="{{paginateUrl}}"> <input type="hidden" id="paginateUrl" value="{{paginateUrl}}">
<input type="hidden" id="searchTerm" value="{{searchTerm}}"> <input type="hidden" id="searchTerm" value="{{searchTerm}}">
<div class="col-md-12"> <div class="col-md-12">