recipeData.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. Recipe.findOne({_id: req.body.id})
  64. .then((recipe)=>{
  65. recipe.name = req.body.name;
  66. recipe.price = req.body.price;
  67. recipe.ingredients = req.body.ingredients;
  68. return recipe.save()
  69. })
  70. .then((response)=>{
  71. return res.json({});
  72. })
  73. .catch((err)=>{
  74. return res.json("Error: unable to update your recipe");
  75. })
  76. }
  77. }