terrible/app/utils/event-source.js

15 lines
453 B
JavaScript
Raw Permalink Normal View History

2024-03-11 23:03:35 -05:00
import {stream} from './stream';
export function eventSource(request, init) {
const headers = new Headers();
headers.set('Content-Type', 'text/event-stream');
return stream(request, headers, (send, close) => {
const encoder = new TextEncoder();
function sendEvent(data, event = 'message') {
send(encoder.encode(`event: ${event}\n`));
send(encoder.encode(`data: ${data}\n\n`));
}
return init(sendEvent, close);
});
}