hyperpop.js/demo/demo.ts

85 lines
2.5 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) {
2021-10-12 22:38:51 +00:00
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);
2021-10-12 22:38:51 +00:00
detailsEl.append(preEl);
return detailsEl;
}
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}`);
}
}
2021-10-12 22:57:24 +00:00
function setupForm(selector: string, listener: (event: Event) => 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();
2021-10-12 22:57:24 +00:00
showResponse(statusEl, listener(event));
});
}
setupForm("#token", () => dummy(token()));
setupForm("#save-token", async () => {
localStorage.token = token();
});
setupForm("#productos", () => getProductos(token(), {}));
setupForm("#price", () => getPrices(token(), {}));
2021-10-12 22:57:24 +00:00
setupForm("#price-by-customer", (event) =>
getPricesByCustomer(token(), { filter: (event.target! as any).filter.value })
);
setupForm("#customer", () => getCustomers(token(), {}));