writing.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. const Comment = require("../models/comment.js");
  2. const fs = require("fs");
  3. module.exports = {
  4. listDirectories: function(req, res){
  5. const searchDir = function(path, currentObject){
  6. let response = fs.readdirSync(path);
  7. for(let i = 0; i < response.length; i++){
  8. if(response[i].includes(".") === false){
  9. let newPath = `${path}/${response[i]}`;
  10. let newObject = ({
  11. name: response[i].replace(/-/g, " "),
  12. path: newPath.substring(newPath.indexOf("/writing") + 7, newPath.length),
  13. contents: []
  14. });
  15. currentObject.contents.push(newObject);
  16. searchDir(newPath, newObject);
  17. }
  18. }
  19. return currentObject;
  20. }
  21. let result = searchDir(`${__dirname}/content`, {
  22. contents: []
  23. });
  24. return res.json(result.contents[0].contents);
  25. },
  26. /*
  27. GET: return all comments for the specific article
  28. req.params.article = String
  29. response = [Comment]
  30. */
  31. getComments: function(req, res){
  32. Comment.aggregate([
  33. {$match: {
  34. article: req.params.article
  35. }},
  36. {$sort: {
  37. date: -1
  38. }}
  39. ])
  40. .then((comments)=>{
  41. return res.json(comments);
  42. })
  43. .catch((err)=>{
  44. return res.json("Couldn't retrieve the comments");
  45. });
  46. },
  47. /*
  48. POST: create a new comment
  49. req.body = {
  50. article: String,
  51. name: String,
  52. content: String,
  53. date: Date
  54. }
  55. response = Comment
  56. */
  57. createComment: function(req, res){
  58. let comment = new Comment({
  59. article: req.body.article,
  60. name: req.body.name,
  61. content: req.body.content,
  62. date: new Date(req.body.date)
  63. });
  64. comment.save()
  65. .then((comment)=>{
  66. return res.json(comment);
  67. })
  68. .catch((err)=>{
  69. return res.json("Couldn't create your comment");
  70. });
  71. }
  72. }