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.

119 lines
3.0 KiB

  1. const mysql = require('mysql');
  2. const sanitizer = require('sanitizer');
  3. var Promise = require('promise');
  4. const con = mysql.createConnection({
  5. host: "localhost",
  6. user: "blog_user",
  7. password: "password",
  8. database: "blog_name"
  9. });
  10. con.connect(function(err) {
  11. if (err) throw err;
  12. console.log("Connected!");
  13. });
  14. /**
  15. * Function used to query the database for records
  16. *
  17. * @param sqlStatement
  18. * @returns {Array}
  19. */
  20. var fetch = function(sqlStatement)
  21. {
  22. console.log("sql fetch method called");
  23. return new Promise(function(resolve, reject)
  24. {
  25. con.query(sqlStatement, function (err, result)
  26. {
  27. if (err)
  28. {
  29. console.log(err);
  30. reject();
  31. }
  32. console.log(result);
  33. resolve(result);
  34. });
  35. });
  36. };
  37. module.exports=
  38. {
  39. /**
  40. * Function used to use insert statements into the database
  41. *
  42. * Don't worry, the input gets sanitized
  43. *
  44. * @param sqlStatement
  45. * @return the id of the new record - if there is one
  46. */
  47. insert : function(sqlStatement)
  48. {
  49. con.query((sqlStatement), function (err, result)
  50. {
  51. if (err)
  52. {
  53. console.log(err);
  54. return 0;
  55. }
  56. return result.insertId;
  57. });
  58. },
  59. /**
  60. * Not to be mistaken for getPostData() in @file utils/utils.js,
  61. * this function extracts a post entry from the sql server
  62. *
  63. * @param requestURL url user used to request blog post
  64. * @return {*} the entry found in the data base -- if any
  65. */
  66. getPost : function(requestURL)
  67. {
  68. return new Promise(function(resolve, reject)
  69. {
  70. var splitURL = requestURL.split("/");
  71. var q = "select * from categories where url='" + splitURL[1] + "'";
  72. fetch(q).then(function (result_category)
  73. {
  74. console.log(result_category);
  75. if(result_category.length != 0)
  76. {
  77. q = "select * from posts where category_id='" + result_category[0].category_id + "' and url='" + splitURL[2] + "'";
  78. console.log(q);
  79. fetch(q).then(function (result_posts)
  80. {
  81. console.log(result_posts);
  82. if(result_posts != 0)
  83. {
  84. resolve(result_posts[0]);
  85. }
  86. else
  87. {
  88. resolve(0);
  89. }
  90. });
  91. }
  92. else
  93. {
  94. resolve(0);
  95. }
  96. });
  97. });
  98. },
  99. /**
  100. * Function used to retrieve all categories when making the sidebar
  101. *
  102. * @return {Promise<Response> | * | Array}
  103. */
  104. getCategories: function()
  105. {
  106. var q = "select * from categories";
  107. return fetch(q);
  108. }
  109. };