summaryrefslogtreecommitdiffstats
path: root/static/api-client.js
blob: 4a1b81eb2297519d907241e3468f13b20c9990b7 (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
/* jshint esversion: 2024, module: true */

/**
 * API Client for network operations
 * @class ApiClient
 */
class ApiClient {
    /**
     * API utility function
     * @method request
     * @param {string} path - API endpoint
     * @param {Object} [options] - Fetch options
     * @returns {Promise<Response>}
     */
    async request(path, options = {}) {
        const response = await fetch(path, options);

        if (!response.ok) {
            const text = await response.text();
            throw new Error(`${response.status} ${text}`);
        }

        return response;
    }

    /**
     * GET request returning JSON
     * @method get
     * @param {string} path - API endpoint
     * @returns {Promise<Object>}
     */
    async get(path) {
        const response = await this.request(path);
        return response.json();
    }

    /**
     * GET request returning text
     * @method getText
     * @param {string} path - API endpoint
     * @returns {Promise<string>}
     */
    async getText(path) {
        const response = await this.request(path);
        return response.text();
    }

    /**
     * POST request with JSON body
     * @method post
     * @param {string} path - API endpoint
     * @param {Object} [data] - Request body
     * @returns {Promise<Object>}
     */
    async post(path, data = null) {
        const options = {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
        };

        if (data) {
            options.body = JSON.stringify(data);
        }

        const response = await this.request(path, options);
        return response.json();
    }
}

export { ApiClient };