Last active
December 10, 2015 18:18
-
-
Save hayes/4473641 to your computer and use it in GitHub Desktop.
a quick way to get access to compound routing/controllers through socket.io
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
var sio = require('socket.io'); | |
var fn = function () {}; | |
var http = require('http'); | |
module.exports = function (compound) { | |
var app = compound.app; | |
var server = http.createServer(app); | |
compound.server = server; | |
var io = compound.io = sio.listen(server); | |
var cookieParser, session, router; | |
app.stack.forEach(function (m) { | |
switch (m.handle.name) { | |
case 'cookieParser': | |
cookieParser = m.handle; | |
break | |
case 'session': | |
session = m.handle; | |
case 'router': | |
router = m.handle; | |
break; | |
} | |
}); | |
io.set('authorization', function (req, accept) { | |
// check if there's a cookie header | |
if (!req.headers.cookie) { | |
// if there isn't, turn down the connection with a message | |
// and leave the function. | |
return accept('No cookie transmitted.', false); | |
} | |
req.on = fn; | |
req.removeListener = function () { | |
delete req.on; | |
}; | |
req.originalUrl = '/'; | |
cookieParser(req, null, function (err) { | |
if (err) return accept('Error in cookie parser', false); | |
session(req, {on: fn, end: fn}, function (err) { | |
accept(null, true); | |
}); | |
}); | |
}); | |
io.sockets.on('connection', function (socket) { | |
var hs = socket.handshake; | |
console.log('A socket with userId ' + hs.sessionID + ' connected!'); | |
socket.on('disconnect', function () { | |
console.log('A socket with sessionID ' + hs.sessionID | |
+ ' disconnected!'); | |
// clear the socket interval to stop refreshing the session | |
}); | |
['get', 'post', 'put', 'delete'].forEach(function (method) { | |
socket.on(method, function(path) { | |
var res = Array.prototype.pop.call(arguments), | |
data = arguments[1] || {}; | |
data = typeof data == 'object' ? data : {}; | |
if(typeof path == 'string') { | |
try { | |
req = socketRequest(method, path, data, res); | |
router(req, req.res); | |
} catch(err) { | |
res(err) | |
} | |
} else { | |
res('invalid arguments'); | |
} | |
}); | |
}); | |
socket.join(hs.sessionID); | |
}); | |
var socketRequest = function(method, url, data, fn) { | |
var req = Object.create(app.request), | |
res = req.res = Object.create(app.response); | |
res.req = res; | |
req.method = method; | |
req.url = url; | |
req.app = res.app = app; | |
req.params = data; | |
res.end = function(body) { | |
fn(body, this.statusCode, this._headers); | |
} | |
return req; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment