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.

98 lines
2.6 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. const utils = require('../utils/utils.js');
  2. const sql = require('../utils/sql');
  3. const qs = require('querystring');
  4. const Promise = require('promise');
  5. /**
  6. * Displays all the categories in the database
  7. * @param res
  8. * @return {*|Promise}
  9. */
  10. var printCategories = function(res)
  11. {
  12. res.write("<div class=\"blogPost p-2 \">");
  13. res.write("<h1 class=\"text-center\">Categories</h1>");
  14. res.write("<div class=\"\"><table class=\"table table-striped\">");
  15. res.write("<thead class=\"thead-dark\">");
  16. res.write("<tr>");
  17. res.write("<td>Name</td><td>URL</td><td>Edit</td>");
  18. res.write("</tr></thead><tbody>");
  19. return new Promise(function(resolve, reject)
  20. {
  21. sql.getCategories().then(function(categories)
  22. {
  23. categories.forEach(function(c)
  24. {
  25. res.write("<tr>");
  26. res.write("<td>" + c.name + "</td>");
  27. res.write("<td>" + c.url + "</td>");
  28. res.write("<td>" + c.category_id + "</td>");
  29. res.write("</tr>");
  30. });
  31. res.write("</tbody></table></div></div>");
  32. resolve();
  33. })
  34. });
  35. };
  36. /**
  37. * Checks for post data regarding adding a new category.
  38. * If a post is made with add_category, it parses the url-- replaces spaces
  39. * with dashes -- and calls a insert method on the database
  40. *
  41. * @param res
  42. * @param postData
  43. * @return {*|Promise}
  44. */
  45. var processPost = function(res, postData)
  46. {
  47. return new Promise(function(resolve, reject)
  48. {
  49. var post = qs.parse(postData);
  50. if(post.add_category)
  51. {
  52. var url = post.add_category.split(" ").join("-").toLowerCase();
  53. var q = "insert into categories (name, url) values " +
  54. "('" + post.add_category + "','" + url + "')";
  55. if(sql.insert(q) != 0)
  56. {
  57. console.log("category added");
  58. }
  59. else
  60. {
  61. console.log("error adding category");
  62. }
  63. }
  64. resolve(postData);
  65. });
  66. };
  67. module.exports=
  68. {
  69. main: function(res, postData)
  70. {
  71. res.write("<div class=\"col-md-6\">");
  72. return new Promise(function(resolve, reject)
  73. {
  74. utils.include(res, "./admin/addCategory.html");
  75. printCategories(res).then(function()
  76. {
  77. //console.write("categories finished");
  78. return processPost(res, postData);
  79. }).then(function()
  80. {
  81. res.write("</div>");
  82. resolve(postData);
  83. }).catch(function(err)
  84. {
  85. console.log(err);
  86. })
  87. });
  88. }
  89. };