product.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { beforeUnloadHandler } from "../app.js";
  2. async function getJSONData(response) {
  3. if (response.status === 420) {
  4. window.removeEventListener("beforeunload", beforeUnloadHandler);
  5. window.location.replace("/");
  6. }
  7. if (!response.ok) {
  8. const errorData = await response.json()
  9. throw new Error(errorData.message || `Error del servidor: ${response.status}`);
  10. }
  11. const data = await response.json();
  12. return data.data;
  13. }
  14. async function sendOrder(order, token) {
  15. try {
  16. const response = await fetch("/api/orders/send", {
  17. method: "POST",
  18. headers: {
  19. "Content-Type": "application/json",
  20. "Authorization": `Bearer ${token}`
  21. },
  22. body: JSON.stringify(order)
  23. });
  24. return await getJSONData(response);
  25. } catch (error) {
  26. console.error("Error al enviar la orden:", error);
  27. throw error;
  28. }
  29. }
  30. export async function freeBeer(token, tableNumber) {
  31. try {
  32. const response = await fetch("/api/users/reward", {
  33. method: "POST",
  34. headers: {
  35. "Content-Type": "application/json",
  36. "Authorization": `Bearer ${token}`
  37. },
  38. body: JSON.stringify({ tableNumber })
  39. });
  40. return await getJSONData(response);
  41. } catch (error) {
  42. console.error("Error al obtener cerveza gratis:", error);
  43. throw error;
  44. }
  45. }
  46. async function getProducts(token){
  47. const response = await fetch("/api/products?status=1", {
  48. headers: {
  49. "Content-Type": "application/json",
  50. "Authorization": `Bearer ${token}`
  51. }
  52. });
  53. const data = await getJSONData(response);
  54. data.products.map(product => {
  55. if (product.promotion) {
  56. product.price = product.promotion.price;
  57. }
  58. })
  59. return data.products;
  60. }
  61. export {sendOrder, getProducts}