ingredientData.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. const Merchant = require("../models/merchant");
  2. const Ingredient = require("../models/ingredient");
  3. module.exports = {
  4. //GET - gets a list of all database ingredients
  5. //Returns:
  6. // ingredients: list containing all ingredients
  7. getIngredients: function(req, res){
  8. Ingredient.find()
  9. .then((ingredients)=>{
  10. return res.json(ingredients);
  11. })
  12. .catch((err)=>{
  13. return res.json("Error: unable to retrieve ingredients");
  14. });
  15. },
  16. //TODO - Redirect to merchantData.js rather than adding here
  17. //POST - create a single ingredient and then add to the merchant
  18. //Inputs:
  19. // req.body.ingredient: full ingredient to create (name, category, unit)
  20. // req.body.quantity: quantity of ingredient for merchant
  21. //Returns:
  22. // item: ingredient and quantity
  23. createIngredient: function(req, res){
  24. if(!req.session.user){
  25. req.session.error = "Must be logged in to do that";
  26. return res.redirect("/");
  27. }
  28. Ingredient.create(req.body.ingredient)
  29. .then((ingredient)=>{
  30. Merchant.findOne({_id: req.session.user})
  31. .then((merchant)=>{
  32. let item = {
  33. ingredient: ingredient,
  34. quantity: req.body.quantity
  35. }
  36. merchant.inventory.push(item);
  37. merchant.save()
  38. .then((merchant)=>{
  39. return res.json(item);
  40. })
  41. .catch((err)=>{
  42. return res.json("Error: ingredient could not be saved");
  43. });
  44. })
  45. .catch((err)=>{
  46. return res.json("Error: could not retrieve user data");
  47. });
  48. })
  49. .catch((err)=>{
  50. return res.json("Error: could not create new ingredient");
  51. });
  52. }
  53. }