Advertisement
Guest User

Untitled

a guest
Jul 17th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const jwtDecode = require('jwt-decode');
  2. /**
  3.  * This utility provides a bunch of functions to handle sockets in an easier way.
  4.  * This class uses the singleton pattern.
  5.  * This way we dont need to pass the io to the constructor several times too.
  6.  */
  7. class SocketUtility {
  8.   /**
  9.    * This class uses the singleton pattern.
  10.    * This way we dont need to pass the io to the constructor several times too.
  11.    * @param {SocketIO.Server} io the socket.io server reference. Only the first time this
  12.    * parameter is actually used. All later calls ignore it and simply return the first instance of the class.
  13.    */
  14.   constructor(io) {
  15.     if (!!SocketUtility.instance) {
  16.       return SocketUtility.instance;
  17.     }
  18.     SocketUtility.instance = this;
  19.  
  20.     this.io = io;
  21.     this.socketsList = [];
  22.  
  23.     return this;
  24.   }
  25.  
  26.   /**
  27.    * Add a pair user/socket to the list of sockets handled by the utility class.
  28.    * @param {*} user The user id.
  29.    * @param {*} socket The newly created socket.
  30.    * @param {string} room If this parameter is passed, the user will join a room with the given name.
  31.    */
  32.   addSocket(user, socket, room) {
  33.     if (!this.socketExists(user)) {
  34.       this.socketsList.push({'user': user, 'socket': socket});
  35.  
  36.       if (room) {
  37.         socket.join(room);
  38.       }
  39.     }
  40.   }
  41.  
  42.   /**
  43.    * Remove a socket from the list of sockets.
  44.    * @param {*} socket The socket to be removed.
  45.    */
  46.   removeSocket(socket) {
  47.     this.socketsList = this.socketsList.filter((elem) => {
  48.       return elem.socket != socket;
  49.     });
  50.   }
  51.  
  52.   /**
  53.    * Fetch a socket associated with the given user. If nothing is found undefined is returned.
  54.    * @param {*} user The user id.
  55.    * @returns the socket associated with the user or undefined.
  56.    */
  57.   getSocket(user) {
  58.     const socket = this.socketsList.find((socket) => {
  59.       return socket.user == user;
  60.     });
  61.  
  62.     return socket?socket.socket:undefined;
  63.   }
  64.  
  65.   /**
  66.    * Checks if a user exists in the list of sockets.
  67.    * @param {*} user The user id.
  68.    */
  69.   socketExists(user) {
  70.     return this.getSocket(user) != undefined;
  71.   }
  72.  
  73.   /**
  74.    * If the user's socket exist he joins the room
  75.    * @param {*} user The user id.
  76.    * @param {*} room The room name
  77.    */
  78.   joinRoom(user, room) {
  79.     if (this.socketExists(user)) {
  80.       this.getSocket(user).join(room);
  81.     }
  82.   }
  83.  
  84.   /**
  85.    * If the user's socket exist and he's in the room, he leaves it
  86.    * @param {*} user The user id.
  87.    * @param {*} room The room name
  88.    */
  89.   leaveRoom(user, room) {
  90.     if (this.socketExists(user)) {
  91.       const socket = this.getSocket(user);
  92.  
  93.       if (Object.keys(socket.rooms).includes(room)) {
  94.         socket.leave(room);
  95.       }
  96.     }
  97.   }
  98.  
  99.   /**
  100.    * Broadcast a message to all connected sockets.
  101.    * @param {string} event The event to be broadcasted
  102.    * @param {*} data The message broadcasted. Can be a simple string or even a json payload.
  103.    */
  104.   broadcast(event, data) {
  105.     this.io.sockets.emit(event, data);
  106.   }
  107.  
  108.   /**
  109.    * If the user is connected a message will be sent to him.
  110.    * @param {string} event The event to be broadcasted
  111.    * @param {*} data The message broadcasted. Can be a simple string or even a json payload.
  112.    * @param {*} user The receiver user id.
  113.    */
  114.   sendTo(event, data, user) {
  115.     if (this.socketExists(user)) {
  116.       this.getSocket(user).emit(event, data);
  117.     }
  118.   }
  119.  
  120.   /**
  121.    *
  122.    * @param {string} event The event to be broadcasted
  123.    * @param {*} data The message broadcasted. Can be a simple string or even a json payload.
  124.    * @param {string} room The name of the room where the message will be broadcasted.
  125.    */
  126.   roomBroadcast(event, data, room) {
  127.     // First i check that the room exists
  128.     if (this.io.sockets.adapter.rooms.hasOwnProperty(room)) {
  129.       this.io.to(room).emit(event, data);
  130.     }
  131.   }
  132.  
  133.   /**
  134.    * Call this function the first time you instantiate the class in order to setup
  135.    * and catch the basic events.
  136.    */
  137.   setup() {
  138.     this.io.on('connection', (socket) => {
  139.       socket.on(this.USER_AUTHENTICATED_EVENT, (token) => {
  140.         try {
  141.           const decodedToken = jwtDecode(token);
  142.           this.addSocket(decodedToken._id, socket, decodedToken.role);
  143.         } catch (error) {
  144.           console.log(error);
  145.         }
  146.       });
  147.  
  148.       socket.on(this.USER_SIGNED_OUT_EVENT, (token) => {
  149.         try {
  150.           const decodedToken = jwtDecode(token);
  151.           socket.join('test');
  152.           console.log(Object.keys(socket.rooms));
  153.           socket.leave('test');
  154.           console.log(Object.keys(socket.rooms));
  155.         } catch (error) {
  156.           console.log(error);
  157.           console.log('Invalid token after connection via socket.io');
  158.         }
  159.       });
  160.  
  161.       socket.on('disconnect', () => {
  162.         this.removeSocket(socket);
  163.       });
  164.     });
  165.   }
  166.  
  167.   /**
  168.    * Return the event associated with a user that has succesfully authenticated.
  169.    */
  170.   get USER_AUTHENTICATED_EVENT() {
  171.     return 'user-authenticated';
  172.   }
  173.  
  174.   /**
  175.    * Return the event associated with a user that has succesfully authenticated.
  176.    */
  177.   get USER_SIGNED_OUT_EVENT() {
  178.     return 'user-signed-out';
  179.   }
  180.  
  181.   /**
  182.    * Return the event associated with a change in status of a table (usually from free to occupied and viceversa).
  183.    */
  184.   get TABLE_STATUS_CHANGED_EVENT() {
  185.     return 'table-status-changed';
  186.   }
  187.  
  188.   /**
  189.    * Return the event associated with a new order submitted to the system.
  190.    */
  191.   get ORDER_ADDED_EVENT() {
  192.     return 'order-added';
  193.   }
  194.  
  195.   /**
  196.    * Return the event associated with a change of an order's status.
  197.    */
  198.   get ORDER_STATUS_CHANGED_EVENT() {
  199.     return 'order-status-changed';
  200.   }
  201. }
  202.  
  203. module.exports = {SocketUtility};
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement