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.

96 lines
2.6 KiB

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("<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. resolve();
  31. })
  32. });
  33. };
  34. /**
  35. * Checks for post data regarding adding a new category.
  36. * If a post is made with add_category, it parses the url-- replaces spaces
  37. * with dashes -- and calls a insert method on the database
  38. *
  39. * @param res
  40. * @param postData
  41. * @return {*|Promise}
  42. */
  43. var processPost = function(res, postData)
  44. {
  45. return new Promise(function(resolve, reject)
  46. {
  47. var post = qs.parse(postData);
  48. if(post.add_category)
  49. {
  50. var url = post.add_category.split(" ").join("-").toLowerCase();
  51. var q = "insert into categories (name, url) values " +
  52. "('" + post.add_category + "','" + url + "')";
  53. if(sql.insert(q) != 0)
  54. {
  55. console.log("category added");
  56. }
  57. else
  58. {
  59. console.log("error adding category");
  60. }
  61. }
  62. resolve(postData);
  63. });
  64. };
  65. module.exports=
  66. {
  67. main: function(res, postData)
  68. {
  69. res.write("<div class=\"w3-third w3-container\">");
  70. return new Promise(function(resolve, reject)
  71. {
  72. utils.include(res, "./admin/addCategory.html");
  73. printCategories(res).then(function()
  74. {
  75. //console.write("categories finished");
  76. return processPost(res, postData);
  77. }).then(function()
  78. {
  79. res.write("</div>");
  80. resolve(postData);
  81. }).catch(function(err)
  82. {
  83. console.log(err);
  84. })
  85. });
  86. }
  87. };