Created
June 17, 2016 09:29
-
-
Save kripod/b16a72f73e05a3203e5498083f3922ea to your computer and use it in GitHub Desktop.
SocketHandler base class for Primus
This file contains hidden or 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
class SocketHandler { | |
get room() { | |
return this.primus.rooms(this.roomName); | |
} | |
constructor(primus, roomName, actionHandlers, disconnectionHandler) { | |
this.primus = primus; | |
this.roomName = roomName; | |
primus.on('connection', (spark) => { | |
spark.on('data', ({ room, action, payload = {} }) => { | |
// Only handle messages which are sent to the room | |
if (room !== roomName) return; | |
// Forward payload to the corresponding action handler | |
const actionHandler = actionHandlers[action]; | |
if (actionHandler) { | |
actionHandler(spark, payload); | |
} | |
}); | |
}); | |
primus.on('disconnection', (spark) => { | |
if (disconnectionHandler) { | |
disconnectionHandler(spark, {}); | |
} | |
}); | |
} | |
} | |
module.exports = SocketHandler; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment