socketio / socket.io

Realtime application framework (Node.JS server)
https://socket.io
MIT License
61.04k stars 10.11k forks source link

can't access an object's properties after passing into a socket #3460

Closed ctfrancia closed 5 years ago

ctfrancia commented 5 years ago

Note: for support questions, please use one of these channels: stackoverflow or slack

For bug reports and feature requests for the Swift client, please open an issue there.

For bug reports and feature requests for the Java client, please open an issue there.

You want to:

Current behaviour

What is actually happening? I can't access an object's key/value pair after passing it into the socket.

Steps to reproduce (if the current behaviour is a bug)

Note: the best way (and by that we mean the only way) to get a quick answer is to provide a failing test case by forking the following fiddle.

Expected behaviour

What is expected?

Setup

Other information (e.g. stacktraces, related issues, suggestions how to fix)

const io = require('../chat.index').io;
const redis = require('socket.io-redis');
const globalUsers = {};

io.adapter(redis({host: '127.0.0.1', port: 6379}));

/* object sent in
{
  recipient: "christian",
  content: "hi"
}
*/
module.exports = socket =>  {
  socket.on('message', (data, callback) => {
    const { recipient } = data;
    console.log('data --> ', data); // <--- Object that was sent in
    console.log('recipient -->', recipient); // <-- undefined
    console.log('data.recipient -->', data.recipient); //<-- undefined
    console.log('globalUsers -->', globalUsers); //<---object of users
    if (recipient in globalUsers) {
        socket.to(globalUsers[recipient]).volatile.emit('message', data);
    } else {
      console.log('not found :(', globalUsers); //<--- always here since undefined
    }
  });
}
ctfrancia commented 5 years ago

this is the output from the terminal:

data -->  {
  recipient: "christian",
  content: "hi"
}
recipient --> undefined
data.recipient --> undefined
globalUsers --> {
   christian: 'igi-K6FauBbf50G4AAAA',
  john: 'MiehwQ2NCSvsQNH-AAAB',
}
not found :( {
   christian: 'igi-K6FauBbf50G4AAAA',
  john: 'MiehwQ2NCSvsQNH-AAAB',
}