ingredientData.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. unitType: category for the unit (mass, volume, length)
  24. },
  25. quantity: quantity of ingredient for current merchant,
  26. defaultUnit: default unit of measurement to display
  27. }
  28. Returns:
  29. Same as above, with the _id
  30. */
  31. createIngredient: function(req, res){
  32. if(!req.session.user){
  33. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  34. return res.redirect("/");
  35. }
  36. let validation = Validator.ingredient(req.body.ingredient);
  37. if(validation !== true){
  38. return res.json(validation);
  39. }
  40. validation = Validator.quantity(req.body.quantity);
  41. if(validation !== true){
  42. return res.json(validation);
  43. }
  44. let ingredientPromise = Ingredient.create((req.body.ingredient));
  45. let merchantPromise = Merchant.findOne({_id: req.session.user});
  46. let newIngredient;
  47. Promise.all([ingredientPromise, merchantPromise])
  48. .then((response)=>{
  49. newIngredient = {
  50. ingredient: response[0],
  51. quantity: req.body.quantity,
  52. defaultUnit: req.body.defaultUnit
  53. }
  54. response[1].inventory.push(newIngredient);
  55. return response[1].save();
  56. })
  57. .then((response)=>{
  58. return res.json(newIngredient);
  59. })
  60. .catch((err)=>{
  61. console.log(err);
  62. return res.json("ERROR: UNABLE TO CREATE NEW INGREDIENT");
  63. });
  64. }
  65. }