Created
January 31, 2012 10:08
-
-
Save pgherveou/1709737 to your computer and use it in GitHub Desktop.
Socket io middelware
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
io = require 'socket.io' | |
io.Socket::onEvent = (ev, cbs...) -> | |
@on ev, (args...) -> | |
cbList = cbs.slice() | |
# set callback parameter if any | |
fn = args[args.length-1] if typeof args[args.length-1] is 'function' | |
# set data parameter if any | |
data = args[0] unless args.length is 1 and fn | |
# add cxt parameter | |
cxt = socket: @, session: @handshake.session | |
next = (err) -> | |
if err | |
console.error err.toString() | |
fn err.toString() if fn | |
else | |
cb = cbList.shift() | |
return cb cxt, data, next if cbList.length | |
return cb cxt, data, fn if cb | |
next() | |
# usage | |
# use onEvent instead of on | |
# each middleware is defined with a (cxt, data, next) -> | |
# pass an Error to next if something went wrong to stop the chain | |
# build your callback function with a (cxt, data [, fn]) -> | |
# this function could be defined in a separate module and then referenced | |
# in your main file in the body of your sio.sockets.on 'connection', (socket) -> | |
# cxt can hold event contextual data that each middleware could extend | |
# cxt.socket reference your socket | |
# cxt.session could reference your express session if you define it as described here http://www.danielbaulig.de/socket-ioexpress/ | |
# data, fn are the usual parameters | |
# passing middleware | |
md1 = (cxt, data, next) -> | |
console.log "OK middleware ..." | |
cxt.bar = "foo" | |
next() | |
# failing middleware | |
md2 = (cxt, data, next) -> | |
console.log "KO middleware ..." | |
next new Error "Error!!!! dont tell me why" | |
# this one should pass | |
socket.onEvent 'customEvent', md1, (cxt, data, fn) -> # ... | |
# this one should fail | |
socket.onEvent 'otherEvent', md1, md2, (cxt, data, fn) -> # ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment