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.

79 lines
2.0 KiB

  1. const mysql = require('mysql');
  2. const sanitizer = require('sanitizer');
  3. const con = mysql.createConnection({
  4. host: "localhost",
  5. user: "blog_user",
  6. password: "password",
  7. database: "blog_name"
  8. });
  9. con.connect(function(err) {
  10. if (err) throw err;
  11. console.log("Connected!");
  12. });
  13. module.exports=
  14. {
  15. /**
  16. * Function used to query the database for records
  17. *
  18. * @param sqlStatement
  19. * @returns {Array}
  20. */
  21. fetch : function(sqlStatement)
  22. {
  23. con.query(sqlStatement, function (err, result)
  24. {
  25. if (err) throw err;
  26. return result;
  27. });
  28. return [];
  29. },
  30. /**
  31. * Function used to use insert statements into the database
  32. *
  33. * Don't worry, the input gets sanitized
  34. *
  35. * @param sqlStatement
  36. * @return the id of the new record - if there is one
  37. */
  38. insert : function(sqlStatement)
  39. {
  40. con.query(sanitizer.sanitize(sqlStatement), function (err, result)
  41. {
  42. if (err)
  43. {
  44. console.log(err);
  45. return 0;
  46. }
  47. return result.insertId;
  48. });
  49. },
  50. /**
  51. * Not to be mistaken for getPostData() in @file utils/utils.js,
  52. * this function extracts a post entry from the sql server
  53. *
  54. * @param requestURL url user used to request blog post
  55. * @return {*} the entry found in the data base -- if any
  56. */
  57. getPost : function(requestURL)
  58. {
  59. var splitURL = requestURL.split("/");
  60. var result_category = this.fetch("select * from categories " +
  61. "where url='" + splitURL[1] + "'");
  62. if(result_category.length != 0)
  63. {
  64. var result_posts = this.fetch("select * from posts where" +
  65. "category_id='" + result_category[0].category_id + "' " +
  66. "and url='" + splitURL[2] + "'");
  67. if(result_posts.length != 0)
  68. {
  69. return result_posts[0];
  70. }
  71. }
  72. return 0;
  73. }
  74. };