io.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. let session = cache.findRow('sessions', 'id', socket.sessionId);
  33. // if the action set 'session' to null, that means they want to delete it
  34. if (session === null) delete socket.sessionId;
  35. // call the action, passing it the session, and the arguments socket.io passed us
  36. actions[namespace][action].apply(null, [session].concat(args).concat([
  37. (result) => {
  38. // store the session id, which we use later when the user disconnects
  39. if (name == 'users.login' && result.user) socket.sessionId = result.user.sessionId;
  40. // respond to the socket with our message
  41. cb(result);
  42. }
  43. ]));
  44. })
  45. })
  46. });
  47. socket.emit('ready');
  48. });
  49. cb();
  50. }
  51. };