about summary refs log tree commit diff stats
path: root/src/http.ts
blob: 6fd5c176e00ea4d9452c5482b924159664ec38c4 (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
151
152
153
154
155
156
157
158
159
160
161
162
'use strict';

declare class HttpError extends Error {
    status?: number;
    responseText?: string;
}

declare interface Http {
    setCsrfToken(token: string): void;
    get(url: string): Promise<HttpResponse>;
    post(url: string, body: Record<string, string>): Promise<HttpResponse>;
    blob(url: string): Promise<HttpBlobResponse>;
    text(url: string): Promise<HttpTextResponse>;
}

declare interface HttpResponse {
    data: any;
    ok: boolean;
    status: number;
}

declare interface HttpBlobResponse {
    blob: Blob;
    ok: boolean;
    status: number;
}

declare interface HttpTextResponse {
    text: string;
    ok: boolean;
    status: number;
}

/**
 * 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');
 */
class Http {
    private static _csrfToken = '';

    /**
     * Set the CSRF token for subsequent requests.
     * @param token - The CSRF token string.
     */
    static setCsrfToken(token: string): void {
        Http._csrfToken = token;
    }

    /**
     * Append query parameters to a URL string.
     * @private
     */
    private static _appendParams(url: string, params: Record<string, string> | null | undefined): string {
        if (!params || Object.keys(params).length === 0) return url;
        const separator = url.includes('?') ? '&' : '?';
        const query = new URLSearchParams(params as Record<string, string>).toString();
        return `${url}${separator}${query}`;
    }

    /**
     * Throw a structured error for failed HTTP responses.
     * @private
     */
    private static _throwHttpError(resp: Response): never {
        const err = new Error(`HTTP ${resp.status}: ${resp.statusText}`) as HttpError;
        (err as any).status = resp.status;
        (err as any).responseText = '';
        // Read error body asynchronously — don't block the throw
        resp.text().then((t: string) => { (err as any).responseText = t; }).catch(() => {
            /* ignore */
        });
        throw err;
    }

    /**
     * Perform a GET request. Returns parsed JSON.
     * @param params - Optional query parameters.
     */
    static async get(url: string, params: Record<string, string> | null = null): Promise<HttpResponse> {
        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 body - Form-encoded body parameters.
     */
    static async post(url: string, body: Record<string, string>): Promise<HttpResponse> {
        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 params - Optional query parameters.
     */
    static async blob(url: string, params: Record<string, string> | null = null): Promise<HttpBlobResponse> {
        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 params - Optional query parameters.
     */
    static async text(url: string, params: Record<string, string> | null = null): Promise<HttpTextResponse> {
        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 };
    }
}