Last active
September 7, 2020 12:09
-
-
Save sperand-io/7688d388a895e37fe4bb to your computer and use it in GitHub Desktop.
Koa EventSource Streaming (SSE)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const PassThrough = require('stream').PassThrough; | |
const Router = require('koa-66'); | |
const router = new Router(); | |
const Koa = require('koa'); | |
const app = new Koa(); | |
// ... | |
const sse = (event, data) => { | |
return `event:${ event }\ndata: ${ data }\n\n` | |
} | |
router.get(`/json/data/:source`, ctx => { | |
const stream = new PassThrough(); | |
const { source } = ctx.params; | |
const { db } = app.context; // or whatever :) | |
const reader = db.createReader(source); // or whatever :) | |
const send = (data) => { | |
let { type, msg } = data; // or whatever :) | |
stream.write(sse(type, msg)); | |
} | |
reader.on('data', send); | |
ctx.req.on('close', () => ctx.res.end()); | |
ctx.req.on('finish', () => ctx.res.end()); | |
ctx.req.on('error', () => ctx.res.end()); | |
ctx.type = 'text/event-stream'; | |
ctx.body = stream; | |
}); | |
app.use(router.routes()); | |
app.listen(3000); |
ctx.req.on('close', () => ctx.res.end());
ctx.req.on('finish', () => ctx.res.end());
ctx.req.on('error', () => ctx.res.end());
fixes the issue @sclark39 mentioned
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@sclark39, sse() needs to be a function declaration to work from where it's placed. Otherwise, try:
Defining sse() before it's called should fix the problem.