Advertisement
Guest User

Untitled

a guest
Apr 3rd, 2020
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const axios = require("axios");
  2. const socketio = require("socket.io");
  3. let users = {};
  4.  
  5. exports.setupWebsocket = server => {
  6.   const io = socketio(server);
  7.   console.log("Iniciando webSocket...");
  8.  
  9.   io.on("connection", socket => {
  10.     console.log("Recebendo conexão no socket");
  11.     const { id } = socket;
  12.     const { channel } = socket.handshake.query;
  13.  
  14.     console.log(id, channel);
  15.  
  16.     const timestamp = Date.now();
  17.  
  18.     if (!users[channel]) {
  19.       users[channel] = [];
  20.     }
  21.  
  22.     users[channel].push(id);
  23.  
  24.     socket.on("ducity", async function(obj) {
  25.       const { channel, content, user } = obj;
  26.       console.log( obj );
  27.  
  28.       axios.post('http://localhost:3000/webservices/chats/addMessage', {
  29.         channel: obj.channel,
  30.         content: obj.content,
  31.         user: obj.user,
  32.         timestamp: timestamp
  33.       }, {
  34.         headers: {
  35.           api_secret: 'duc17y@2020#r1ch4rd__'
  36.         }
  37.       })
  38.       .then((res) => {
  39.         console.log(`statusCode: ${res.statusCode}`)
  40.       })
  41.       .catch((error) => {
  42.         console.error(error)
  43.       });
  44.  
  45.       if (!!users[channel]) {
  46.         if (users[channel].length > 0) {
  47.           users[channel].forEach(socketId => {
  48.             io.to(`${socketId}`).emit("ducity", {
  49.               content,
  50.               user,
  51.               timestamp
  52.             });
  53.           });
  54.         }
  55.       }
  56.     });
  57.   });
  58. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement