made a function to generate a websocket endpoint to reduce boilerplate
This commit is contained in:
44
src/lib/server/endpoint.ts
Normal file
44
src/lib/server/endpoint.ts
Normal 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
|
||||||
|
};
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user