Spaces:
Runtime error
Runtime error
File size: 1,707 Bytes
cd6f98e |
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 |
import { env } from "../env/client.mjs";
type TextStream = ReadableStreamDefaultReader<Uint8Array>;
const fetchData = async <T>(
url: string,
body: T,
accessToken: string
): Promise<TextStream | undefined> => {
url = env.NEXT_PUBLIC_BACKEND_URL + url;
const response = await fetch(url, {
method: "POST",
cache: "no-cache",
keepalive: true,
headers: {
"Content-Type": "application/json",
Accept: "text/event-stream",
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify(body),
});
if (response.status === 409) {
const error = (await response.json()) as { error: string; detail: string };
throw new Error(error.detail);
}
return response.body?.getReader();
};
async function readStream(reader: TextStream): Promise<string | null> {
const result = await reader.read();
return result.done ? null : new TextDecoder().decode(result.value);
}
async function processStream(
reader: TextStream,
onStart: () => void,
onText: (text: string) => void,
shouldClose: () => boolean
): Promise<void> {
onStart();
while (true) {
if (shouldClose()) {
await reader.cancel();
return;
}
const text = await readStream(reader);
if (text === null) break;
onText(text);
}
}
export const streamText = async <T>(
url: string,
body: T,
accessToken: string,
onStart: () => void,
onText: (text: string) => void,
shouldClose: () => boolean // Event handler to close connection early
) => {
const reader = await fetchData(url, body, accessToken);
if (!reader) {
console.error("Reader is undefined!");
return;
}
await processStream(reader, onStart, onText, shouldClose);
};
|