recipeData.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 recipe = new Recipe({
  22. merchant: req.session.user,
  23. name: req.body.name,
  24. price: Math.round(req.body.price * 100),
  25. ingredients: req.body.ingredients
  26. });
  27. Merchant.findOne({_id: req.session.user})
  28. .then((merchant)=>{
  29. merchant.recipes.push(recipe);
  30. merchant.save()
  31. .catch((err)=>{
  32. return res.json("Error: unable to save recipe");
  33. });
  34. })
  35. .catch((err)=>{
  36. return res.json("Error: unable to retrieve user data");
  37. })
  38. recipe.save()
  39. .then((newRecipe)=>{
  40. return res.json(newRecipe);
  41. })
  42. .catch((err)=>{
  43. return res.json("Error: unable to save new ingredient");
  44. });
  45. },
  46. /*
  47. PUT - Update a single recipe
  48. req.body = {
  49. id: id of recipe,
  50. name: name of recipe,
  51. price: price of recipe,
  52. ingredients: [{
  53. ingredient: id of ingredient,
  54. quantity: quantity of ingredient in recipe
  55. }]
  56. }
  57. */
  58. updateRecipe: function(req, res){
  59. if(!req.session.user){
  60. req.session.error = "Must be logged in to do that";
  61. return res.redirect("/");
  62. }
  63. console.log(req.body);
  64. Recipe.findOne({_id: req.body.id})
  65. .then((recipe)=>{
  66. recipe.name = req.body.name;
  67. recipe.price = req.body.price;
  68. recipe.ingredients = req.body.ingredients;
  69. return recipe.save()
  70. })
  71. .then((response)=>{
  72. return res.json({});
  73. })
  74. .catch((err)=>{
  75. return res.json("Error: unable to update your recipe");
  76. })
  77. }
  78. }