blog.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. const Blog = require("../models/blog.js");
  2. const Uploader = require("../models/uploader.js");
  3. const createId = require("./createId.js");
  4. module.exports = {
  5. /*
  6. POST: create a new blog
  7. req.body = {
  8. uploader: String (uploader id)
  9. password: String
  10. title: String
  11. tags: String
  12. blog: String
  13. }
  14. req.files = {
  15. thumbnail: File
  16. }
  17. redirect to home
  18. */
  19. create: function(req, res){
  20. Uploader.findOne({_id: req.body.uploader})
  21. .then((uploader)=>{
  22. if(uploader === "none") throw "uploader";
  23. if(req.body.password !== uploader.password) throw "pass";
  24. let fileString = `/thumbNails/${createId(25)}`;
  25. req.files.thumbnail.mv(`${__dirname}/..${fileString}`);
  26. let blog = new Blog({
  27. writer: uploader._id,
  28. title: req.body.title,
  29. tags: req.body.tags.split(","),
  30. thumbnail: fileString,
  31. article: req.body.blog
  32. });
  33. return blog.save();
  34. })
  35. .then((blog)=>{
  36. return res.redirect("/");
  37. })
  38. .catch((err)=>{});
  39. },
  40. /*
  41. GET: get a list of all blogs
  42. response = [Blog]
  43. */
  44. getBlogs: function(req, res){
  45. Blog.aggregate([{$project: {article: 0}}])
  46. .then((blogs)=>{
  47. return res.json(blogs);
  48. })
  49. .catch((err)=>{
  50. return res.json("ERROR: could not retrieve blog data");
  51. });
  52. },
  53. /*
  54. GET: gets a single blog
  55. req.params.id = String (blog id)
  56. response = Blog
  57. */
  58. getBlog: function(req, res){
  59. Blog.findOne({_id: req.params.id})
  60. .populate("writer")
  61. .then((blog)=>{
  62. return res.json(blog);
  63. })
  64. .catch((err)=>{
  65. return res.json("Error: unable to retrieve the blog");
  66. });
  67. }
  68. }