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.

99 lines
2.7 KiB

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. var 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("<h1 class=\"w3-text-teal w3-center\">Categories</h1>");
  13. res.write("<div class=\"w3-responsive w3-card-4\"><table class=\"w3-table w3-striped w3-bordered\"><thead>");
  14. res.write("<tr class=\"w3-teal\">");
  15. res.write("<td>Name</td><td>URL</td><td>Edit</td>");
  16. res.write("</tr></thead><tbody>");
  17. return new Promise(function(resolve, reject)
  18. {
  19. sql.getCategories().then(function(categories)
  20. {
  21. categories.forEach(function(c)
  22. {
  23. res.write("<tr>");
  24. res.write("<td>" + c.name + "</td>");
  25. res.write("<td>" + c.url + "</td>");
  26. res.write("<td>" + c.category_id + "</td>");
  27. res.write("</tr>");
  28. });
  29. res.write("</tbody></table></div>");
  30. console.log("resolved");
  31. resolve();
  32. })
  33. });
  34. };
  35. /**
  36. * Checks for post data regarding adding a new category.
  37. * If a post is made with add_category, it parses the url-- replaces spaces
  38. * with dashes -- and calls a insert method on the database
  39. *
  40. * @param res
  41. * @param postData
  42. * @return {*|Promise}
  43. */
  44. var processPost = function(res, postData)
  45. {
  46. return new Promise(function(resolve, reject)
  47. {
  48. var post = qs.parse(postData);
  49. if(post.add_category)
  50. {
  51. var url = post.add_category.replace(/ /i, "-");
  52. url = url.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=\"w3-third w3-container\">");
  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();
  83. }).catch(function(err)
  84. {
  85. console.log(err);
  86. })
  87. });
  88. }
  89. };