recipeData.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. const Recipe = require("../models/recipe");
  2. const Merchant = require("../models/merchant");
  3. const Validator = require("./validator.js");
  4. module.exports = {
  5. /*
  6. POST - creates a single new recipe
  7. req.body = {
  8. name: name of recipe,
  9. price: price of the recipe,
  10. ingredients: [{
  11. id: id of ingredient,
  12. quantity: quantity of ingredient in recipe
  13. }]
  14. }
  15. Return = newly created recipe in same form as above, with _id
  16. */
  17. createRecipe: function(req, res){
  18. if(!req.session.user){
  19. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  20. return res.redirect("/");
  21. }
  22. let validation = Validator.recipe(req.body);
  23. if(validation !== true){
  24. return res.json(validation);
  25. }
  26. let recipe = new Recipe({
  27. merchant: req.session.user,
  28. name: req.body.name,
  29. price: Math.round(req.body.price * 100),
  30. ingredients: req.body.ingredients
  31. });
  32. Merchant.findOne({_id: req.session.user})
  33. .then((merchant)=>{
  34. merchant.recipes.push(recipe);
  35. merchant.save()
  36. .catch((err)=>{
  37. return res.json("ERROR: UNABLE TO SAVE RECIPE");
  38. });
  39. })
  40. .catch((err)=>{
  41. return res.json("ERROR: UNABLE TO RETRIEVE USER DATA");
  42. });
  43. recipe.save()
  44. .then((newRecipe)=>{
  45. return res.json(newRecipe);
  46. })
  47. .catch((err)=>{
  48. return res.json("ERROR: UNABLE TO SAVE INGREDIENT");
  49. });
  50. },
  51. /*
  52. PUT - Update a single recipe
  53. req.body = {
  54. id: id of recipe,
  55. name: name of recipe,
  56. price: price of recipe,
  57. ingredients: [{
  58. ingredient: id of ingredient,
  59. quantity: quantity of ingredient in recipe
  60. }]
  61. }
  62. */
  63. updateRecipe: function(req, res){
  64. if(!req.session.user){
  65. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  66. return res.redirect("/");
  67. }
  68. let validation = Validator.recipe(req.body);
  69. if(validation !== true){
  70. return res.json(validation);
  71. }
  72. Recipe.findOne({_id: req.body.id})
  73. .then((recipe)=>{
  74. recipe.name = req.body.name;
  75. recipe.price = req.body.price;
  76. recipe.ingredients = req.body.ingredients;
  77. return recipe.save()
  78. })
  79. .then((response)=>{
  80. return res.json({});
  81. })
  82. .catch((err)=>{
  83. return res.json("ERROR: UNABLE TO UPDATE RECIPE");
  84. });
  85. }
  86. }