blog.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. console.log(err);
  40. });
  41. },
  42. /*
  43. GET: get a list of all blogs
  44. response = [Blog]
  45. */
  46. getBlogs: function(req, res){
  47. Blog.aggregate([{$project: {article: 0}}])
  48. .then((blogs)=>{
  49. return res.json(blogs);
  50. })
  51. .catch((err)=>{
  52. return res.json("ERROR: could not retrieve blog data");
  53. });
  54. },
  55. /*
  56. GET: gets a single blog
  57. req.params.id = String (blog id)
  58. response = Blog
  59. */
  60. getBlog: function(req, res){
  61. Blog.findOne({_id: req.params.id})
  62. .populate("writer")
  63. .then((blog)=>{
  64. return res.json(blog);
  65. })
  66. .catch((err)=>{
  67. return res.json("Error: unable to retrieve the blog");
  68. });
  69. }
  70. }