File size: 1,607 Bytes
d012552
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// application/static/js/components/request.js
class Request {
    constructor() {

    }
    async request(method, url, headers = {}, payload = null, stream = false) {
        try {
            const response = await fetch(url, {
                method: method,
                headers: headers,
                body: payload
            });

            if (!response.ok) {
                // It's good practice to handle non-OK responses.
                throw new Error(`Request failed: ${response.status} - ${await response.text()}`);
            }

            if (stream) {
                return this.handleStream(response); // This is correct
            } else {
                // Create an async generator that yields the entire body as a single chunk.
                return (async function*() {
                    const text = await response.text();
                    yield text;
                })(); // Immediately-invoked function expression (IIFE)
            }
        } catch (error) {
            console.error("Request error:", error); // Log the error
            throw error; // Re-throw the error so the caller can handle it
        }
    }

    async *handleStream(response) {
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        while (true) {
            const { done, value } = await reader.read();
            if (done) {
                break;
            }
            const chunk = decoder.decode(value, { stream: true });
            yield chunk;
        }
    }
}

const requests = new Request();
export default requests;