ingredientData.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. if(!Validator.ingredient(req.body.ingredient)){
  36. return res.json("Error: ingredient contains illegal characters");
  37. }
  38. if(!Validator.quantity(req.body.quantity)){
  39. return res.json("Error: inappropriate quantity");
  40. }
  41. let ingredientPromise = Ingredient.create((req.body.ingredient));
  42. let merchantPromise = Merchant.findOne({_id: req.session.user});
  43. let newIngredient;
  44. Promise.all([ingredientPromise, merchantPromise])
  45. .then((response)=>{
  46. newIngredient = {
  47. ingredient: response[0],
  48. quantity: req.body.quantity
  49. }
  50. response[1].inventory.push(newIngredient);
  51. return response[1].save();
  52. })
  53. .then((response)=>{
  54. return res.json(newIngredient);
  55. })
  56. .catch((err)=>{
  57. return res.json("Error: unable to create new ingredient");
  58. });
  59. }
  60. }