currency.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. name: String
  15. value: Number
  16. }
  17. req.files = {
  18. frontImage: Image
  19. backImage: Image
  20. }
  21. redirect: /currency
  22. */
  23. create: function(req, res){
  24. Uploader.findOne({_id: req.body.uploader})
  25. .then((uploader)=>{
  26. if(!uploader) throw "uploader";
  27. if(req.body.password !== uploader.password) throw "pass";
  28. let createImage = (image)=>{
  29. let fileString = `/currencyimages/${createId(25)}.jpg`;
  30. image.mv(`${__dirname}/..${fileString}`);
  31. return fileString;
  32. }
  33. let currency = new Currency({
  34. location: req.body.location,
  35. name: req.body.name,
  36. value: req.body.value,
  37. type: req.body.type,
  38. year: req.body.year,
  39. comment: req.body.comment,
  40. frontImage: createImage(req.files.frontImage),
  41. backImage: createImage(req.files.backImage)
  42. });
  43. return currency.save();
  44. })
  45. .then((currency)=>{
  46. return res.redirect("/currency");
  47. })
  48. .catch((err)=>{
  49. switch(err){
  50. case "uploader": return res.redirect("/");
  51. case "pass": return res.redirect("/");
  52. default:
  53. console.error(err);
  54. return res.redirect("/");
  55. }
  56. });
  57. },
  58. getData: function(req, res){
  59. Currency.find()
  60. .then((currencies)=>{
  61. return res.json(currencies);
  62. })
  63. .catch((err)=>{
  64. console.error(err);
  65. });
  66. }
  67. }