Created
January 9, 2019 16:46
-
-
Save Faizanq/a4d07f1a9624bdf6d3ddd9d4d6cc1b2d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //logic | |
| exports.getProducts = (req, res, next) => { | |
| const page = +req.query.page || 1; | |
| let totalItems; | |
| Product.find() | |
| .countDocuments() | |
| .then(numProducts => { | |
| totalItems = numProducts; | |
| return Product.find() | |
| .skip((page - 1) * ITEMS_PER_PAGE) | |
| .limit(ITEMS_PER_PAGE); | |
| }) | |
| .then(products => { | |
| res.render('shop/product-list', { | |
| prods: products, | |
| pageTitle: 'Products', | |
| path: '/products', | |
| currentPage: page, | |
| hasNextPage: ITEMS_PER_PAGE * page < totalItems, | |
| hasPreviousPage: page > 1, | |
| nextPage: page + 1, | |
| previousPage: page - 1, | |
| lastPage: Math.ceil(totalItems / ITEMS_PER_PAGE) | |
| }); | |
| }) | |
| .catch(err => { | |
| const error = new Error(err); | |
| error.httpStatusCode = 500; | |
| return next(error); | |
| }); | |
| }; | |
| //view | |
| <section class="pagination"> | |
| <% if (currentPage !== 1 && previousPage !== 1) { %> | |
| <a href="?page=1">1</a> | |
| <% } %> | |
| <% if (hasPreviousPage) { %> | |
| <a href="?page=<%= previousPage %>"><%= previousPage %></a> | |
| <% } %> | |
| <a href="?page=<%= currentPage %>" class="active"><%= currentPage %></a> | |
| <% if (hasNextPage) { %> | |
| <a href="?page=<%= nextPage %>"><%= nextPage %></a> | |
| <% } %> | |
| <% if (lastPage !== currentPage && nextPage !== lastPage) { %> | |
| <a href="?page=<%= lastPage %>"><%= lastPage %></a> | |
| <% } %> | |
| </section> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment