made a function to generate a websocket endpoint to reduce boilerplate

This commit is contained in:
2026-05-23 20:14:06 +01:00
parent 5f4436180e
commit 8879c943a4

View File

@@ -0,0 +1,44 @@
export async function generateEndpoint(
startFunction?: (enqueue: (data: any) => void) => void | Promise<void | (() => void)>
) {
let streamController: ReadableStreamDefaultController | null = null;
let cleanupFunction: (() => void) | void = undefined;
const enqueue = (data: any) => {
let transferdata = JSON.stringify(data);
// stringify data and add to controller queue
if (streamController) {
streamController.enqueue(`data: ${transferdata}\n\n`);
} else {
console.log('no controller');
}
};
const stream = new ReadableStream({
async start(controller) {
streamController = controller;
if (startFunction) {
const result = await startFunction(enqueue);
if (typeof result === 'function') {
cleanupFunction = result;
}
}
},
async cancel() {
if (cleanupFunction) cleanupFunction();
}
});
return {
response: new Response(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
'X-Accel-Buffering': 'no'
}
}),
enqueue: enqueue,
controller: streamController
};
}