main
ts 30 lines 931 Bytes
Raw
1 // This file is part of HFS - Copyright 2021-2023, Massimo Melina <a@rejetto.com> - License https://www.gnu.org/licenses/gpl-3.0.txt
2
3 import Koa from 'koa'
4 import { Transform } from 'stream'
5 import { HTTP_OK } from './const'
6
7 export default function createSSE(ctx: Koa.Context) {
8 const { socket } = ctx.req
9 socket.setTimeout(0)
10 socket.setNoDelay(true)
11 socket.setKeepAlive(true)
12 ctx.set({
13 'Content-Type': 'text/event-stream',
14 'Cache-Control': 'no-cache',
15 'Connection': 'keep-alive',
16 'X-Accel-Buffering': 'no', // avoid buffering when reverse-proxied through nginx
17 })
18 ctx.status = HTTP_OK
19 return ctx.body = new Transform({
20 objectMode: true,
21 transform(chunk, encoding, cb) {
22 this.push(`data: ${JSON.stringify(chunk)}\n\n`)
23 cb()
24 },
25 flush(cb) {
26 this.push('data:\n\n')
27 cb()
28 }
29 })
30 }