hyperpop.js/demo/demo.ts

77 lines
2.2 KiB
TypeScript
Raw Normal View History

import {
dummy,
getProductos,
getPrices,
getPricesByCustomer,
getCustomers,
} from "../index.js";
const tokenInput = document.querySelector<HTMLInputElement>("#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 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);
return preEl;
}
async function showResponse(statusEl: Element | null, promise: Promise<any>) {
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<any>) {
const formEl = document.querySelector<HTMLFormElement>(selector);
if (!formEl) throw new Error(`No existe el formulario ${selector}`);
const statusEl = formEl.querySelector<HTMLElement>(".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(), {}));