From 8879c943a42a602a8a2e3759d3f7eefc43618a6f Mon Sep 17 00:00:00 2001 From: voidarc Date: Sat, 23 May 2026 20:14:06 +0100 Subject: [PATCH] made a function to generate a websocket endpoint to reduce boilerplate --- src/lib/server/endpoint.ts | 44 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 src/lib/server/endpoint.ts diff --git a/src/lib/server/endpoint.ts b/src/lib/server/endpoint.ts new file mode 100644 index 0000000..9b97176 --- /dev/null +++ b/src/lib/server/endpoint.ts @@ -0,0 +1,44 @@ +export async function generateEndpoint( + startFunction?: (enqueue: (data: any) => void) => void | Promise 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 + }; +}