recipeData.js 2.7 KB

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