Spaces:
Sleeping
Sleeping
// 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; |