From a475f58defac27f4dff1e0093ec2776b26c0d96c Mon Sep 17 00:00:00 2001 From: "Dustin C. Hatch" Date: Mon, 10 Mar 2025 18:22:32 -0500 Subject: [PATCH] js: Factor out getResponseError utility function This function factors out the logic of extracting an error message from a `Response` object into a reusable utility function. This will allow other pages to use the same logic without duplicating it. --- js/ajaxUtil.ts | 16 ++++++++++++++++ js/receipt-form.ts | 18 +++--------------- 2 files changed, 19 insertions(+), 15 deletions(-) create mode 100644 js/ajaxUtil.ts diff --git a/js/ajaxUtil.ts b/js/ajaxUtil.ts new file mode 100644 index 0000000..df9745b --- /dev/null +++ b/js/ajaxUtil.ts @@ -0,0 +1,16 @@ +export async function getResponseError(r: Response): Promise { + let ct = r.headers.get("Content-Type"); + if (ct && ct.indexOf("json") > -1) { + const json = await r.json(); + if (json.error) { + return json.error; + } + } + const html = await r.text(); + if (html) { + const doc = new DOMParser().parseFromString(html, "text/html"); + return doc.documentElement.textContent ?? ""; + } else { + return r.statusText; + } +} diff --git a/js/receipt-form.ts b/js/receipt-form.ts index f208287..bd7bd24 100644 --- a/js/receipt-form.ts +++ b/js/receipt-form.ts @@ -12,6 +12,7 @@ import CameraInput from "./camera.ts"; import SlButton from "@shoelace-style/shoelace/dist/components/button/button.js"; import { notify, notifyError } from "./alert"; +import { getResponseError } from "./ajaxUtil.js"; const form = document.forms[0]; const cameraInput = form.querySelector("camera-input") as CameraInput; @@ -49,21 +50,8 @@ form.addEventListener("submit", async (evt) => { notify("Successfully uploaded receipt", undefined, undefined, null); window.location.href = "/receipts"; } else { - let ct = r.headers.get("Content-Type"); - if (ct && ct.indexOf("json") > -1) { - const json = await r.json(); - if (json.error) { - notifyError(json.error); - return; - } - } - const html = await r.text(); - if (html) { - const doc = new DOMParser().parseFromString(html, "text/html"); - notifyError(doc.body.textContent ?? ""); - } else { - notifyError(r.statusText); - } + const err = await getResponseError(r); + notifyError(err); } });