about summary refs log tree commit diff stats
path: root/src/http.js
blob: e66888cd5b3ef6a65cc4beb76ace209b2dfe3f82 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
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 };
    }
}