Skip to content

Instantly share code, notes, and snippets.

@loopj
Created October 26, 2012 23:29
Show Gist options
  • Select an option

  • Save loopj/3962169 to your computer and use it in GitHub Desktop.

Select an option

Save loopj/3962169 to your computer and use it in GitHub Desktop.
Connect middleware for pub/sub using server-sent events
//
// Simple pub/sub using redis and server-sent events (EventSource)
//
// Usage:
//
// // Attach the middleware
// redisSse = require("redis-sse");
// app.use(redisSse({redis: yourRedisClient}));
//
// // Set up a subscription to a channel in your route
// app.get("/subscribe-me", function (req, res) {
// req.subscribe("channelName");
// });
//
// That's it! Anything you publish to the redis channel "channelName" will
// be delivered as a server-sent event to the client.
//
exports = module.exports = function(opts) {
return function(req, res, next) {
req.subscribe = function(channel) {
if(!opts.redis) {
throw new Error("You must specify a redis client when using redisSse middleware.");
}
var messageCount = 0;
req.socket.setTimeout(Infinity);
res.statusCode = 200;
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
opts.redis.subscribe(channel);
opts.redis.on("message", function(c, message) {
if (c !== channel) return;
res.write("id: " + messageCount + "\n");
res.write("data: " + message + "\n\n");
messageCount += 1;
});
};
next();
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment