import { dummy, getProductos, getPrices, getPricesByCustomer, getCustomers, } from "../index.js"; const tokenInput = document.querySelector("#token-input")!; if (localStorage.token) { tokenInput.value = localStorage.token; } function token() { return tokenInput.value; } function clear(el: Node) { while (el.firstChild) { el.firstChild.remove(); } } function objectToDom(object: any) { const detailsEl = document.createElement("details"); const summaryEl = document.createElement("summary"); summaryEl.append("JSON"); detailsEl.open = true; detailsEl.append(summaryEl); const preEl = document.createElement("pre"); const codeEl = document.createElement("code"); if (typeof object === "string") { codeEl.append(JSON.stringify(JSON.parse(object), null, 2)); } else if (Object.keys(object).length > 0) { codeEl.append(JSON.stringify(object, null, 2)); } else { codeEl.append(object); } preEl.append(codeEl); detailsEl.append(preEl); return detailsEl; } async function showResponse(statusEl: Element | null, promise: Promise) { if (statusEl) clear(statusEl); try { const response = await promise; if (statusEl) { statusEl.append("¡Funcionó!"); if (response) { statusEl.append(" Respuesta:", objectToDom(response)); } } else alert(`¡Funcionó!${response ? ` Respuesta: ${response}` : ""}`); } catch (error) { if (statusEl) statusEl.append("Hubo un error :(", objectToDom(error)); else alert(`Hubo un error: ${error}`); } } function setupForm(selector: string, listener: () => Promise) { const formEl = document.querySelector(selector); if (!formEl) throw new Error(`No existe el formulario ${selector}`); const statusEl = formEl.querySelector(".status"); if (!statusEl) console.error( `El formulario ${selector} no tiene un .status, voy a reportar los errores con alert()` ); formEl.addEventListener("submit", async (event) => { event.preventDefault(); showResponse(statusEl, listener()); }); } setupForm("#token", () => dummy(token())); setupForm("#save-token", async () => { localStorage.token = token(); }); setupForm("#productos", () => getProductos(token(), {})); setupForm("#price", () => getPrices(token(), {})); setupForm("#price-by-customer", () => getPricesByCustomer(token(), {})); setupForm("#customer", () => getCustomers(token(), {}));