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.

102 lines
2.7 KiB

  1. /** Whiskers template file
  2. * this has stuff for both editing blog and viewing a list of blog*/
  3. const TEMPLATE_FILE = "admin/adminPosts.html";
  4. const includes = require('../includes/includes.js');
  5. const sql = require('../utils/sql');
  6. //parses the post data
  7. const qs = require('querystring');
  8. /**
  9. * Detects if the post data came from the edit form in blog table or edit post
  10. * in the edit post form.
  11. *
  12. * @param postData
  13. * @param renderContext
  14. * @returns {Promise}
  15. */
  16. const processPostData = function(postData, renderContext)
  17. {
  18. return new Promise(function(resolve, reject)
  19. {
  20. var postParsed = qs.parse(postData);
  21. if(postParsed.edit_post)
  22. {
  23. renderContext.editPost = true;
  24. sql.getPostById(postParsed.edit_post).then(function(post)
  25. {
  26. post.published = post.published.toISOString().split('T')[0];
  27. renderContext.post = post;
  28. resolve();
  29. });
  30. }
  31. else if(postParsed.edit_post_2)
  32. {
  33. sql.editPost(postParsed).then(function()
  34. {
  35. resolve();
  36. }).catch(function(error)
  37. {
  38. reject(error);
  39. });
  40. }
  41. else
  42. {
  43. resolve();
  44. }
  45. });
  46. };
  47. /**
  48. * Grabs and appends the list of blog from the SQL database to
  49. * the template context for the template renderer.
  50. *
  51. * @param templateContext
  52. * @returns {Promise}
  53. */
  54. const fetchPostsInformation = function(templateContext)
  55. {
  56. return new Promise(function(resolve, reject)
  57. {
  58. sql.getAllPosts().then(function(posts)
  59. {
  60. templateContext.posts = posts;
  61. resolve();
  62. }).catch(function(error)
  63. {
  64. reject(error);
  65. })
  66. });
  67. };
  68. module.exports=
  69. {
  70. /**
  71. * Fetches context information for the admin blog page and handles post
  72. * data sent regarding editing blog.
  73. *
  74. * @param postData posted by user
  75. * @param templateContext json object used as the template context
  76. * @returns {Promise} renders the template used for this page
  77. */
  78. main: function(postData, templateContext)
  79. {
  80. return new Promise(function(resolve, reject)
  81. {
  82. Promise.all([includes.fetchTemplate(TEMPLATE_FILE),
  83. processPostData(postData, templateContext),
  84. fetchPostsInformation(templateContext)]).then(function(template)
  85. {
  86. resolve(template[0]);
  87. }).catch(function(error)
  88. {
  89. console.log("error in add admin blog.js");
  90. reject(error);
  91. });
  92. });
  93. }
  94. };