This commit is contained in:
@ -132,15 +132,15 @@ export const GET: APIRoute = async ({ request }) => {
|
||||
const stream = new ReadableStream({
|
||||
start(ctrl) {
|
||||
controller = ctrl;
|
||||
// Send initial data immediately to establish connection
|
||||
const message = `data: ${JSON.stringify({ type: "connected", timestamp: Date.now() })}\n\n`;
|
||||
controller.enqueue(encoder.encode(message));
|
||||
},
|
||||
cancel() {
|
||||
// Client disconnected
|
||||
console.log("SSE stream cancelled by client");
|
||||
isClosed = true;
|
||||
if (pollInterval) {
|
||||
clearInterval(pollInterval);
|
||||
pollInterval = null;
|
||||
}
|
||||
cleanup();
|
||||
},
|
||||
});
|
||||
|
||||
@ -196,7 +196,11 @@ export const GET: APIRoute = async ({ request }) => {
|
||||
JSON.stringify(currentTrack) !== JSON.stringify(lastTrackData)
|
||||
) {
|
||||
lastTrackData = currentTrack;
|
||||
sendMessage(currentTrack || { is_playing: false, item: null });
|
||||
sendMessage({
|
||||
type: "track",
|
||||
data: currentTrack || { is_playing: false, item: null },
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (!isClosed) {
|
||||
@ -205,29 +209,48 @@ export const GET: APIRoute = async ({ request }) => {
|
||||
}
|
||||
};
|
||||
|
||||
// Send initial data
|
||||
// Send initial data immediately
|
||||
poll();
|
||||
|
||||
// Poll every 3 seconds
|
||||
pollInterval = setInterval(poll, 3000);
|
||||
|
||||
// Clean up when client disconnects (abort signal)
|
||||
request.signal.addEventListener("abort", () => {
|
||||
console.log("SSE request aborted");
|
||||
isClosed = true;
|
||||
// Send keepalive every 30 seconds to prevent connection timeout
|
||||
const keepaliveInterval = setInterval(() => {
|
||||
if (!isClosed) {
|
||||
sendMessage({ type: "keepalive", timestamp: Date.now() });
|
||||
}
|
||||
}, 30000);
|
||||
|
||||
// Clean up keepalive interval too
|
||||
const cleanup = () => {
|
||||
if (pollInterval) {
|
||||
clearInterval(pollInterval);
|
||||
pollInterval = null;
|
||||
}
|
||||
if (keepaliveInterval) {
|
||||
clearInterval(keepaliveInterval);
|
||||
}
|
||||
};
|
||||
|
||||
// Clean up when client disconnects (abort signal)
|
||||
request.signal.addEventListener("abort", () => {
|
||||
console.log("SSE request aborted");
|
||||
isClosed = true;
|
||||
cleanup();
|
||||
});
|
||||
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache",
|
||||
"Cache-Control": "no-cache, no-store, must-revalidate",
|
||||
Connection: "keep-alive",
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
"Access-Control-Allow-Headers": "Cache-Control",
|
||||
"X-Accel-Buffering": "no",
|
||||
"CF-Cache-Status": "BYPASS",
|
||||
"Transfer-Encoding": "chunked",
|
||||
Vary: "Accept-Encoding",
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
|
Reference in New Issue
Block a user