-
-
Save XGHeaven/77c16a9893958da53bee11a188bdeb62 to your computer and use it in GitHub Desktop.
Koa EventSource Streaming (SSE)
This file contains 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(); | |
// ... | |
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; | |
}); | |
const sse = (event, data) => { | |
return `event:${ event }\ndata: ${ data }\n\n` | |
} | |
app.use(router.routes()); | |
app.listen(3000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment