gallery.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. tags: [String]
  11. }
  12. req.files = [images]
  13. */
  14. create: function(req, res){
  15. Uploader.findOne({_id: req.body.uploader})
  16. .then((uploader)=>{
  17. if(uploader === null) throw "uploader";
  18. if(req.body.password !== uploader.password) throw "pass";
  19. let gallery = new Gallery({
  20. owner: uploader._id,
  21. tags: req.body.tags.split(","),
  22. images: []
  23. });
  24. let files = req.files.images;
  25. for(let i = 0; i < files.length; i++){
  26. let fileString = `/galleryImages/${createId(25)}.jpg`;
  27. files[i].mv(`${__dirname}/..${fileString}`);
  28. gallery.images.push(fileString);
  29. };
  30. return gallery.save();
  31. })
  32. .then((gallery)=>{
  33. return res.redirect("/");
  34. })
  35. .catch((err)=>{
  36. if(err === "uploader") return res.json("You do not have permission to upload");
  37. if(err === "pass") return res.json("Incorrect password");
  38. return res.json("ERROR: something went wrong");
  39. })
  40. }
  41. }