Skip to content

Instantly share code, notes, and snippets.

@dvv
Created June 28, 2011 17:25
Show Gist options
  • Save dvv/1051658 to your computer and use it in GitHub Desktop.
Save dvv/1051658 to your computer and use it in GitHub Desktop.
middleware reuse for socket.io
...
var stack = [
// serve static content
Stack.static(__dirname + '/public', 'index.html', {
maxAge: 0,
//cacheThreshold: 16384
}),
// dynamic content requires session
sessionHandler = require('cookie-sessions')({
session_key: 'sid',
secret: 'change-me-in-production-env',
path: '/',
timeout: 86400000
}),
// process request body
Stack.body(),
// process RESTful access
restHandler = Stack.rest('/', {
context: context
}),
// handle signin/signout
auth(),
];
...
var io = require('socket.io-context');
var ws = io.Context(http, {
name: '',
'log level': 3,
// authorize and authenticate
authorization: function(data, cb) {
var req = {headers: data.headers};
sessionHandler(req, {}, function() {
data.session = req.session || {};
cb(null, true);
});
}
});
ws.on('connection', function(client) {
console.log('CONNECTED', client.handshake.session.user);
client.update(context);
...
//
// bridge from socket.io events to standard ReST handler
//
function empty() {}
client.on('rest', function(url, method, body, ack) {
console.error('REST', arguments);
// fake request object
var req = {
method: method,
url: url,
body: body
};
// fake response object
var res = {
writeHead: function(status) {
if (status !== 200) {
typeof ack === 'function' && ack(status);
res.end = empty;
}
},
end: function(data) {
typeof ack === 'function' && ack(null, data);
},
fake: true
};
// reuse vanilla middleware layer
restHandler(req, res, function() {
typeof ack === 'function' && ack(404);
});
});
//
//
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment