about summary refs log tree commit diff stats
path: root/src/http.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/http.ts')
-rw-r--r--src/http.ts150
1 files changed, 150 insertions, 0 deletions
diff --git a/src/http.ts b/src/http.ts
new file mode 100644
index 0000000..e66888c
--- /dev/null
+++ b/src/http.ts
@@ -0,0 +1,150 @@
+// @ts-check
+
+'use strict';
+
+/**
+ * @class
+ * @description Static HTTP client wrapping fetch with CSRF support.
+ *
+ * Usage:
+ *   const resp = await Http.get('backend.php?op=list');
+ *   const data = resp.data;
+ *
+ *   await Http.post('backend.php', { op: 'storelastread', id: 42 });
+ *
+ *   const { blob } = await Http.blob('backend.php?op=download&id=42');
+ */
+// eslint-disable-next-line no-unused-vars
+class Http {
+    /** @private @type {string} */
+    static _csrfToken = '';
+
+    /**
+     * Set the CSRF token for subsequent requests.
+     * @param {string} token
+     */
+    static setCsrfToken(token) {
+        Http._csrfToken = token;
+    }
+
+    /**
+     * Append query parameters to a URL string.
+     * @private
+     * @param {string} url
+     * @param {Record<string, string> | null | undefined} params
+     * @returns {string}
+     */
+    static _appendParams(url, params) {
+        if (!params || Object.keys(params).length === 0) return url;
+        const separator = url.includes('?') ? '&' : '?';
+        const query = new URLSearchParams(params).toString();
+        return `${url}${separator}${query}`;
+    }
+
+    /**
+     * Throw a structured error for failed HTTP responses.
+     * @private
+     * @param {Response} resp
+     * @returns {never}
+     */
+    static _throwHttpError(resp) {
+        /** @type {HttpError} */
+        const err = new Error(`HTTP ${resp.status}: ${resp.statusText}`);
+        err.status = resp.status;
+        err.responseText = '';
+        // Read error body asynchronously — don't block the throw
+        resp.text().then((t) => { err.responseText = t; }).catch(() => {
+            /* ignore */
+        });
+        throw err;
+    }
+
+    /**
+     * Perform a GET request. Returns parsed JSON.
+     * @param {string} url
+     * @param {Record<string, string> | null} [params] - optional query parameters
+     * @returns {Promise<HttpResponse>}
+     */
+    static async get(url, params) {
+        const urlWithParams = Http._appendParams(url, params);
+        const resp = await fetch(urlWithParams, {
+            method: 'GET',
+            credentials: 'same-origin',
+        });
+
+        if (!resp.ok) {
+            Http._throwHttpError(resp);
+        }
+
+        const data = await resp.json();
+        return { data, ok: true, status: resp.status };
+    }
+
+    /**
+     * Perform a POST request with form-encoded body. Returns parsed JSON.
+     * @param {string} url
+     * @param {Record<string, string>} body
+     * @returns {Promise<HttpResponse>}
+     */
+    static async post(url, body) {
+        const params = new URLSearchParams(body);
+        if (Http._csrfToken) {
+            params.append('csrf_token', Http._csrfToken);
+        }
+
+        const resp = await fetch(url, {
+            method: 'POST',
+            credentials: 'same-origin',
+            body: params, // passing URLSearchParams here gives us automatic application/x-www-form-urlencoded content type
+        });
+
+        if (!resp.ok) {
+            Http._throwHttpError(resp);
+        }
+
+        const data = await resp.json();
+        return { data, ok: true, status: resp.status };
+    }
+
+    /**
+     * Perform a GET request and return the body as a Blob.
+     * @param {string} url
+     * @param {Record<string, string> | null} [params] - optional query parameters
+     * @returns {Promise<HttpBlobResponse>}
+     */
+    static async blob(url, params) {
+        const urlWithParams = Http._appendParams(url, params);
+        const resp = await fetch(urlWithParams, {
+            method: 'GET',
+            credentials: 'same-origin',
+        });
+
+        if (!resp.ok) {
+            Http._throwHttpError(resp);
+        }
+
+        const blob = await resp.blob();
+        return { blob, ok: true, status: resp.status };
+    }
+
+    /**
+     * Perform a GET request and return the body as plain text.
+     * @param {string} url
+     * @param {Record<string, string> | null} [params] - optional query parameters
+     * @returns {Promise<HttpTextResponse>}
+     */
+    static async text(url, params) {
+        const urlWithParams = Http._appendParams(url, params);
+        const resp = await fetch(urlWithParams, {
+            method: 'GET',
+            credentials: 'same-origin',
+        });
+
+        if (!resp.ok) {
+            Http._throwHttpError(resp);
+        }
+
+        const text = await resp.text();
+        return { text, ok: true, status: resp.status };
+    }
+}