Personal blog written from scratch using Node.js, Bootstrap, and MySQL. https://jrtechs.net
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
2.3 KiB

  1. /**
  2. * Determines if the requested page is out of bounds
  3. *
  4. * @param page current page
  5. * @param postsPerPage - number of blog rendered on each page
  6. * @param totalPosts - total blog in this category/total
  7. * @returns {boolean} if this is a valid page
  8. */
  9. const isValidPage = function(page, postsPerPage, totalPosts)
  10. {
  11. return !(page === 0 || page -1 >= totalPosts/postsPerPage);
  12. };
  13. module.exports=
  14. {
  15. /**
  16. * Renders two buttons on the bottom of the page to
  17. * go to the left or right
  18. *
  19. * Used by the home page and categories pages
  20. * @param baseURL -- base url of page being rendered
  21. * @param currentPage -- current page being rendered
  22. * @param postsPerPage -- number of blog on each page
  23. * @param totalPosts -- total amount of blog in the category
  24. * @returns {Promise} promise which renders the buttons
  25. */
  26. main: function(baseURL, currentPage, postsPerPage, totalPosts, templateContext)
  27. {
  28. if(typeof currentPage == "undefined")
  29. currentPage = 1;
  30. currentPage = Number(currentPage);
  31. if(!isValidPage(currentPage, postsPerPage, totalPosts))
  32. {
  33. reject("Invalid Page");
  34. }
  35. var paginationObject = new Object();
  36. var nextPage = currentPage + 1;
  37. var previousPage = currentPage - 1;
  38. if (isValidPage(previousPage, postsPerPage, totalPosts))
  39. {
  40. paginationObject.previous = {url: baseURL + "?page=" + previousPage};
  41. }
  42. if (isValidPage(nextPage, postsPerPage, totalPosts))
  43. {
  44. paginationObject.next = {url: baseURL + "?page=" + nextPage};
  45. }
  46. var page = 1;
  47. var pages = [];
  48. while(isValidPage(page, postsPerPage, totalPosts))
  49. {
  50. if(page === currentPage)
  51. {
  52. pages.push({isCurrent: true, number: page})
  53. }
  54. else
  55. {
  56. pages.push({number: page, url: baseURL + "?page=" + page})
  57. }
  58. page = page + 1;
  59. }
  60. paginationObject.pages = pages;
  61. templateContext.pagination = paginationObject;
  62. }
  63. };