currency.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. const Currency = require("../models/currency.js");
  2. const Uploader = require("../models/uploader.js");
  3. const createId = require("./createId.js");
  4. module.exports = {
  5. /*
  6. POST: create a new currency
  7. req.body = {
  8. uploader: String (id of owner)
  9. password: String
  10. location: String
  11. type: String (paper/coin)
  12. year: Number
  13. comment: String
  14. }
  15. req.files = {
  16. frontImage: Image
  17. backImage: Image
  18. }
  19. redirect: /currency
  20. */
  21. create: function(req, res){
  22. Uploader.findOne({_id: req.body.uploader})
  23. .then((uploader)=>{
  24. if(!uploader) throw "uploader";
  25. if(req.body.password !== uploader.password) throw "pass";
  26. let createImage = (image)=>{
  27. console.log(image);
  28. let fileString = `/currencyimages/${createId(25)}.jpg`;
  29. image.mv(`${__dirname}/..${fileString}`);
  30. return fileString;
  31. }
  32. let currency = new Currency({
  33. location: req.body.location,
  34. type: req.body.type,
  35. year: req.body.year,
  36. comment: req.body.comment,
  37. frontImage: createImage(req.files.frontImage),
  38. backImage: createImage(req.files.backImage)
  39. });
  40. return currency.save();
  41. })
  42. .then((currency)=>{
  43. return res.redirect("/currency");
  44. })
  45. .catch((err)=>{
  46. switch(err){
  47. case "uploader": return res.redirect("/");
  48. case "pass": return res.redirect("/");
  49. default:
  50. console.error(err);
  51. return res.redirect("/");
  52. }
  53. });
  54. }
  55. }