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.

75 lines
2.5 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. var strippedURL = baseURL.split("?page=")[0];
  39. if (isValidPage(previousPage, postsPerPage, totalPosts))
  40. {
  41. paginationObject.previous = {url: strippedURL + "?page=" + previousPage};
  42. }
  43. if (isValidPage(nextPage, postsPerPage, totalPosts))
  44. {
  45. paginationObject.next = {url: strippedURL + "?page=" + nextPage};
  46. }
  47. var page = 1;
  48. var pages = [];
  49. while(isValidPage(page, postsPerPage, totalPosts))
  50. {
  51. if(page === 11)
  52. {
  53. break;
  54. }
  55. if(page === currentPage)
  56. {
  57. pages.push({isCurrent: true, number: page})
  58. }
  59. else
  60. {
  61. pages.push({number: page, url: strippedURL + "?page=" + page})
  62. }
  63. page = page + 1;
  64. }
  65. paginationObject.pages = pages;
  66. templateContext.pagination = paginationObject;
  67. }
  68. };