ingredientData.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. const Merchant = require("../models/merchant");
  2. const Ingredient = require("../models/ingredient");
  3. const Validator = require("./validator.js");
  4. module.exports = {
  5. //GET - gets a list of all database ingredients
  6. //Returns:
  7. // ingredients: list containing all ingredients
  8. getIngredients: function(req, res){
  9. Ingredient.find()
  10. .then((ingredients)=>{
  11. return res.json(ingredients);
  12. })
  13. .catch((err)=>{
  14. return res.json("ERROR: UNABLE TO RETRIEVE INGREDIENTS");
  15. });
  16. },
  17. /*
  18. POST - create a single ingredient and then add to the merchant
  19. req.body = {
  20. ingredient: {
  21. name: name of ingredient,
  22. category: category of ingredient,
  23. unit: unit measurement of ingredient
  24. },
  25. quantity: quantity of ingredient for current merchant
  26. }
  27. Returns:
  28. Same as above, with the _id
  29. */
  30. createIngredient: function(req, res){
  31. if(!req.session.user){
  32. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  33. return res.redirect("/");
  34. }
  35. let validation = Validator.ingredient(req.body.ingredient);
  36. if(validation !== true){
  37. return res.json(validation);
  38. }
  39. validation = Validator.quantity(req.body.quantity);
  40. if(validation !== true){
  41. return res.json(validation);
  42. }
  43. let ingredientPromise = Ingredient.create((req.body.ingredient));
  44. let merchantPromise = Merchant.findOne({_id: req.session.user});
  45. let newIngredient;
  46. Promise.all([ingredientPromise, merchantPromise])
  47. .then((response)=>{
  48. newIngredient = {
  49. ingredient: response[0],
  50. quantity: req.body.quantity
  51. }
  52. response[1].inventory.push(newIngredient);
  53. return response[1].save();
  54. })
  55. .then((response)=>{
  56. return res.json(newIngredient);
  57. })
  58. .catch((err)=>{
  59. return res.json("ERROR: UNABLE TO CREATE NEW INGREDIENT");
  60. });
  61. }
  62. }