newIngredient.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. module.exports = {
  2. display: function(){
  3. document.querySelector("#newIngName").value = "";
  4. document.querySelector("#newIngCategory").value = "";
  5. document.querySelector("#newIngQuantity").value = 0;
  6. },
  7. submit: function(){
  8. let unitSelector = document.getElementById("unitSelector");
  9. let options = document.querySelectorAll("#unitSelector option");
  10. let unit = unitSelector.value;
  11. let newIngredient = {
  12. ingredient: {
  13. name: document.getElementById("newIngName").value,
  14. category: document.getElementById("newIngCategory").value,
  15. unitType: options[unitSelector.selectedIndex].getAttribute("type"),
  16. },
  17. quantity: controller.convertToMain(unit, document.querySelector("#newIngQuantity").value),
  18. defaultUnit: unit
  19. }
  20. let loader = document.getElementById("loaderContainer");
  21. loader.style.display = "flex";
  22. fetch("/ingredients/create", {
  23. method: "POST",
  24. headers: {
  25. "Content-Type": "application/json;charset=utf-8"
  26. },
  27. body: JSON.stringify(newIngredient)
  28. })
  29. .then((response) => response.json())
  30. .then((response)=>{
  31. if(typeof(response) === "string"){
  32. banner.createError(response);
  33. }else{
  34. merchant.editIngredients([{
  35. ingredient: new Ingredient(
  36. response.ingredient._id,
  37. response.ingredient.name,
  38. response.ingredient.category,
  39. response.ingredient.unitType,
  40. response.defaultUnit,
  41. merchant
  42. ),
  43. quantity: response.quantity
  44. }]);
  45. banner.createNotification("INGREDIENT CREATED");
  46. }
  47. })
  48. .catch((err)=>{
  49. banner.createError("SOMETHING WENT WRONG. PLEASE REFRESH THE PAGE");
  50. })
  51. .finally(()=>{
  52. loader.style.display = "none";
  53. });
  54. }
  55. }