gallery.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. const Uploader = require("../models/uploader.js");
  2. const Gallery = require("../models/gallery.js");
  3. const createId = require("./createId.js");
  4. module.exports = {
  5. /*
  6. POST: create a new gallery
  7. req.body = {
  8. uploader: String (id of owner)
  9. password: String
  10. title: String
  11. tags: [String]
  12. }
  13. req.files = [images]
  14. */
  15. create: function(req, res){
  16. Uploader.findOne({_id: req.body.uploader})
  17. .then((uploader)=>{
  18. if(uploader === null) throw "uploader";
  19. if(req.body.password !== uploader.password) throw "pass";
  20. let gallery = new Gallery({
  21. owner: uploader._id,
  22. title: req.body.title,
  23. tags: req.body.tags.split(","),
  24. images: []
  25. });
  26. let files = req.files.images;
  27. for(let i = 0; i < files.length; i++){
  28. let fileString = `/galleryImages/${createId(25)}.jpg`;
  29. files[i].mv(`${__dirname}/..${fileString}`);
  30. gallery.images.push(fileString);
  31. };
  32. return gallery.save();
  33. })
  34. .then((gallery)=>{
  35. return res.redirect("/");
  36. })
  37. .catch((err)=>{
  38. if(err === "uploader") return res.json("You do not have permission to upload");
  39. if(err === "pass") return res.json("Incorrect password");
  40. return res.json("ERROR: something went wrong");
  41. });
  42. },
  43. getGalleries: function(req, res){
  44. Gallery.find()
  45. .then((galleries)=>{
  46. return res.json(galleries);
  47. })
  48. .catch((err)=>{
  49. return res.json("ERROR: could not fetch galleries");
  50. });
  51. },
  52. /*
  53. GET: fetch the data for a single gallery
  54. req.params.id = String (gallery id)
  55. response = Gallery
  56. */
  57. getGallery: function(req, res){
  58. Gallery.findOne({_id: req.params.id})
  59. .then((gallery)=>{
  60. return res.json(gallery);
  61. })
  62. .catch((err)=>{
  63. return res.json("ERROR: could not fetch gallery");
  64. });
  65. }
  66. }