@opengis/fastify-table
Version:
core-plugins
29 lines (28 loc) • 913 B
JavaScript
/* eslint-disable no-console */
/* eslint-disable no-param-reassign */
export default function eventStream(res) {
if (!res)
return console.log;
const time = Date.now();
// eslint-disable-next-line no-underscore-dangle
if (!res?._headerSent && !res.sent) {
res.raw.writeHead(200, {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
'X-Accel-Buffering': 'no',
});
res.hijack();
}
let prev = time;
function send(mes, finish) {
const t1 = Date.now();
res.raw.write(`data: ${finish ? 'finish' : ''} ${typeof mes === 'object' ? JSON.stringify(mes) : mes} ${t1 - prev}/${t1 - time}ms\n\n`);
prev = t1;
if (finish) {
res.raw.write('data: finish');
res.raw.end('');
}
}
return send;
}