io.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. 'use strict';
  2. // This file contains all the logic for Socket.IO
  3. const app = require('./app');
  4. const actions = require('./actions');
  5. const cache = require('./cache');
  6. module.exports = {
  7. io: null,
  8. init: (cb) => {
  9. this.io = require('socket.io')(app.server);
  10. this.io.on('connection', socket => {
  11. console.log("io: User has connected");
  12. // catch when the socket has been disconnected
  13. socket.on('disconnect', () => {
  14. // remove the user from their current station
  15. if (socket.sessionId) {
  16. actions.stations.leave(socket.sessionId, result => {});
  17. delete socket.sessionId;
  18. }
  19. console.log('io: User has disconnected');
  20. });
  21. // catch errors on the socket (internal to socket.io)
  22. socket.on('error', err => console.log(err));
  23. // have the socket listen for each action
  24. Object.keys(actions).forEach((namespace) => {
  25. Object.keys(actions[namespace]).forEach((action) => {
  26. // the full name of the action
  27. let name = `${namespace}.${action}`;
  28. // listen for this action to be called
  29. socket.on(name, function () {
  30. let args = Array.prototype.slice.call(arguments, 0, -1);
  31. let cb = arguments[arguments.length - 1];
  32. // load the session from the cache
  33. cache.hget('sessions', socket.sessionId, (err, session) => {
  34. if (err && err !== true) {
  35. return cb({
  36. status: 'error',
  37. message: 'An error occurred while obtaining your session'
  38. });
  39. }
  40. // make sure the sockets sessionId isn't set if there is no session
  41. if (socket.sessionId && session === null) delete socket.sessionId;
  42. // call the action, passing it the session, and the arguments socket.io passed us
  43. actions[namespace][action].apply(null, [session].concat(args).concat([
  44. (result) => {
  45. // store the session id
  46. if (name == 'users.login' && result.user) socket.sessionId = result.user.sessionId;
  47. // respond to the socket with our message
  48. cb(result);
  49. }
  50. ]));
  51. });
  52. })
  53. })
  54. });
  55. socket.emit('ready');
  56. });
  57. cb();
  58. }
  59. };