ingredientData.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. /*
  17. POST - create a single ingredient and then add to the merchant
  18. req.body = {
  19. ingredient: {
  20. name: name of ingredient,
  21. category: category of ingredient,
  22. unit: unit measurement of ingredient
  23. },
  24. quantity: quantity of ingredient for current merchant
  25. }
  26. Returns:
  27. Same as above, with the _id
  28. */
  29. createIngredient: function(req, res){
  30. if(!req.session.user){
  31. req.session.error = "Must be logged in to do that";
  32. return res.redirect("/");
  33. }
  34. let ingredientPromise = Ingredient.create((req.body.ingredient));
  35. let merchantPromise = Merchant.findOne({_id: req.session.user});
  36. let newIngredient;
  37. Promise.all([ingredientPromise, merchantPromise])
  38. .then((response)=>{
  39. newIngredient = {
  40. ingredient: response[0],
  41. quantity: req.body.quantity
  42. }
  43. response[1].inventory.push(newIngredient);
  44. return response[1].save();
  45. })
  46. .then((response)=>{
  47. return res.json(newIngredient);
  48. })
  49. .catch((err)=>{
  50. return res.json("Error: unable to create new ingredient");
  51. });
  52. }
  53. }