Book Image

Node.js By Example

Book Image

Node.js By Example

Overview of this book

Table of Contents (18 chapters)
Node.js By Example
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Sending messages to the user's friends only


The last change in our backend dispatches the received chat messages to all the users in our social network. This is of course not really practical, because we may exchange text with people who do not know each other. We have to change our code accordingly so that we send messages only to the users in our friends list.

With Socket.IO, we do not have access to the request and response objects as we do in the backend API by default. This will make the solving of the problem a bit more interesting because we can't recognize the user sending the message. Thankfully, Socket.IO gives us access to the active session. It is in a raw format. So, we will need to parse it and extract the user's profile data. To do this, we will use the cookie Node.js module. Let's add it to the package.json file in the following way:

"dependencies": {
  "cookie": "0.1.2",
  "socket.io": "1.3.3",
  ...
  ...
}

With another npm install in the terminal, we will be able to require...