ingredientData.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. //POST - creates new ingredients from a list
  17. //Inputs:
  18. // req.body: list of ingredients (name, category, unit)
  19. //Returns:
  20. // ingredients: list containing the newly created ingredients
  21. createNewIngredients: function(req, res){
  22. Ingredient.create(req.body)
  23. .then((ingredients)=>{
  24. return res.json(ingredients);
  25. })
  26. .catch((err)=>{
  27. return res.json("Error: new ingredients could not be created");
  28. });
  29. },
  30. //TODO - Redirect to merchantData.js rather than adding here
  31. //POST - create a single ingredient and then add to the merchant
  32. //Inputs:
  33. // req.body.ingredient: full ingredient to create (name, category, unit)
  34. // req.body.quantity: quantity of ingredient for merchant
  35. //Returns:
  36. // item: ingredient and quantity
  37. createIngredient: function(req, res){
  38. if(!req.session.user){
  39. req.session.error = "Must be logged in to do that";
  40. return res.redirect("/");
  41. }
  42. Ingredient.create(req.body.ingredient)
  43. .then((ingredient)=>{
  44. Merchant.findOne({_id: req.session.user})
  45. .then((merchant)=>{
  46. let item = {
  47. ingredient: ingredient,
  48. quantity: req.body.quantity
  49. }
  50. merchant.inventory.push(item);
  51. merchant.save()
  52. .then((merchant)=>{
  53. return res.json(item);
  54. })
  55. .catch((err)=>{
  56. return res.json("Error: ingredient could not be saved");
  57. });
  58. })
  59. .catch((err)=>{
  60. return res.json("Error: could not retrieve user data");
  61. });
  62. })
  63. .catch((err)=>{
  64. return res.json("Error: could not create new ingredient");
  65. });
  66. }
  67. }