Spaces:
Running
Running
Update application/static/js/components/request.js
Browse files
application/static/js/components/request.js
CHANGED
|
@@ -1,38 +1,49 @@
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// application/static/js/components/request.js
|
| 2 |
+
class Request {
|
| 3 |
+
constructor() {
|
| 4 |
+
|
| 5 |
+
}
|
| 6 |
+
async request(method, url, headers = {}, payload = null, stream = false) {
|
| 7 |
+
try {
|
| 8 |
+
const response = await fetch(url, {
|
| 9 |
+
method: method,
|
| 10 |
+
headers: headers,
|
| 11 |
+
body: payload
|
| 12 |
+
});
|
| 13 |
+
|
| 14 |
+
if (!response.ok) {
|
| 15 |
+
// It's good practice to handle non-OK responses.
|
| 16 |
+
throw new Error(`Request failed: ${response.status} - ${await response.text()}`);
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
if (stream) {
|
| 20 |
+
return this.handleStream(response); // This is correct
|
| 21 |
+
} else {
|
| 22 |
+
// Create an async generator that yields the entire body as a single chunk.
|
| 23 |
+
return (async function*() {
|
| 24 |
+
const text = await response.text();
|
| 25 |
+
yield text;
|
| 26 |
+
})(); // Immediately-invoked function expression (IIFE)
|
| 27 |
+
}
|
| 28 |
+
} catch (error) {
|
| 29 |
+
console.error("Request error:", error); // Log the error
|
| 30 |
+
throw error; // Re-throw the error so the caller can handle it
|
| 31 |
+
}
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
async *handleStream(response) {
|
| 35 |
+
const reader = response.body.getReader();
|
| 36 |
+
const decoder = new TextDecoder();
|
| 37 |
+
while (true) {
|
| 38 |
+
const { done, value } = await reader.read();
|
| 39 |
+
if (done) {
|
| 40 |
+
break;
|
| 41 |
+
}
|
| 42 |
+
const chunk = decoder.decode(value, { stream: true });
|
| 43 |
+
yield chunk;
|
| 44 |
+
}
|
| 45 |
+
}
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
const requests = new Request();
|
| 49 |
+
export default requests;
|