forked from koajs/examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
32 lines (25 loc) · 832 Bytes
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const Koa = require('koa');
const app = module.exports = new Koa();
const sse = require('./sse');
const db = require('./db');
app.use(async function(ctx) {
// otherwise node will automatically close this connection in 2 minutes
ctx.req.setTimeout(Number.MAX_VALUE);
ctx.type = 'text/event-stream; charset=utf-8';
ctx.set('Cache-Control', 'no-cache');
ctx.set('Connection', 'keep-alive');
const body = ctx.body = sse();
const stream = db.subscribe('some event');
stream.pipe(body);
// if the connection closes or errors,
// we stop the SSE.
const socket = ctx.socket;
socket.on('error', close);
socket.on('close', close);
function close() {
stream.unpipe(body);
socket.removeListener('error', close);
socket.removeListener('close', close);
}
});
if (!module.parent) app.listen(3000);