writing.js 2.3 KB

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