Skip to content

Instantly share code, notes, and snippets.

@XGHeaven
Forked from sperand-io/index.js
Created April 23, 2017 18:12
Show Gist options
  • Save XGHeaven/77c16a9893958da53bee11a188bdeb62 to your computer and use it in GitHub Desktop.
Save XGHeaven/77c16a9893958da53bee11a188bdeb62 to your computer and use it in GitHub Desktop.
Koa EventSource Streaming (SSE)
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