Skip to content

Instantly share code, notes, and snippets.

@wanming
Last active Nov 26, 2019
Embed
What would you like to do?
sse server
const sseServer = new SSEServer({
url: '/files/:fileGuid/pull'
})
const commentRegister = sseServer.register({
queryKeyword: 'comment',
getRoomId(context: SSEClientContext) {
return context.request.params.fileGuid
},
async fetch (commentId: string, context: any) {
const commentList = await getCommentList(commentId, context.roomId)
return commentList
}
});
commentRegister.on('room:create', (roomId: string) => {
messageBus.subscribe(`comment:${roomId}`)
})
commentRegister.on('room:empty', (roomId: string) => {
messageBus.unsubscribe(`comment:${roomId}`)
})
messageBus.on('new-comment', comment => {
commentRegister.send(comment)
})
// for koa
koaApp.use(sseServer.koaMiddleware())
// for express
expressApp.use(sseServer.expressMiddleware())
// for http handler, like https://github.com/koajs/koa/blob/master/lib/application.js#L141
http.use(sseServer.callback())
// standalone
sseServer.listen(9000)
@NeoyeElf

This comment has been minimized.

Copy link

@NeoyeElf NeoyeElf commented Nov 20, 2019

for koa2

const sseio = require('sse.io-nodejs')

const register = sseio.register({
  // ...
});

// ... register events

app.use(sseio.koaMiddleware());

app.use(async (ctx) => {
   ctx.sseio.start();
   // ...
   ctx.sseio.end();
});
@NeoyeElf

This comment has been minimized.

Copy link

@NeoyeElf NeoyeElf commented Nov 26, 2019

attaches sse.io to a plain Node.JS HTTP server

const server = require('http').createServer();
const sseio = require('sse.io');
const sseServer = sseio.newServer(server, {
  path: '/files/:fileGuid/pull'
})

// ... regist event

server.listen(3000);

standalone

const sseio = require('sse.io');
const sseServer = sseio.newServer({
  path: '/files/:fileGuid/pull'
})

// ... regist event

sseServer.listen(3000);

In conjunction with Express

const app = require('express')();
const server = require('http').createServer(app);
const sseio = require('sse.io');
const sseServer = sseio.newServer(server, {
  path: '/files/:fileGuid/pull'
})

// ... regist event

server.listen(3000);

In conjunction with Koa

const app = require('koa')();
const server = require('http').createServer(app.callback());
const sseio = require('sse.io');
const sseServer = sseio.newServer(server, {
  path: '/files/:fileGuid/pull'
})

// ... regist event

server.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment