writing.js 2.4 KB

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