diff options
| author | Andrew Dolgov <fox@fakecake.org> | 2026-06-16 08:39:10 +0300 |
|---|---|---|
| committer | Andrew Dolgov <fox@fakecake.org> | 2026-06-16 08:39:10 +0300 |
| commit | 09735053c351ea046d237b5746aee366bd5b9b4f (patch) | |
| tree | d84ed79c203f53fa33f0af39c293f58a6a2fcda8 /src/http.js | |
| parent | 24e40b614ca560c65371cd8bb579c950cd14c99f (diff) | |
| download | the-epube-09735053c351ea046d237b5746aee366bd5b9b4f.tar.gz the-epube-09735053c351ea046d237b5746aee366bd5b9b4f.tar.xz | |
migrate to a helper class which wraps fetch operations from using a mishmash of .post/.get/fetch
Diffstat (limited to 'src/http.js')
| -rw-r--r-- | src/http.js | 150 |
1 files changed, 150 insertions, 0 deletions
diff --git a/src/http.js b/src/http.js new file mode 100644 index 0000000..e66888c --- /dev/null +++ b/src/http.js @@ -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 }; + } +} |
