import { beforeUnloadHandler } from "../app.js"; import { showError } from "../utils/error.js"; async function login(email, pin, table) { const response = await fetch("/api/users/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email, pin }) } ); if (response.status == 420) { window.removeEventListener("beforeunload", beforeUnloadHandler); window.location.replace("/"); } if (response.status == 404) { const errorData = await response.json() const data = errorData.message } else if (response.status == 401) { const errorData = await response.json() const data = errorData.message showError(`${data} Intentos restantes: ${errorData.data.attempts_remaining || 0}`); throw new Error(errorData.message); } else if (response.status == 429) { const errorData = await response.json() const data = errorData.message showError(`${data} Intenta más tarde.`); throw new Error(errorData.message); } else if (response.status != 200) { console.error(response.status, response.statusText); const errorData = await response.json() const data = errorData.message showError(`${data}`); throw new Error(data); } const JSONdata = await response.json(); const userData = JSONdata.data; console.log(userData); if (!userData || !userData.token) { showError("Error al iniciar sesión, Intenta mas tarde."); throw new Error("Error al iniciar sesión."); } return userData; } async function existsTable(table) { // Check if table exists const responseTableExists = await fetch(`/api/store/tables/exists?q=${table}`, { method: "GET", headers: { "Content-Type": "application/json" } }); const data = (await responseTableExists.json()).data.exists; return data; } export { login, existsTable };