Currently, the name User, the incorrect name we see inside of the browser that comes from socket.emit function in chat.js:
socket.emit('createMessage', {
from: 'User',
text: messageTextbox.val('')
}, function() {
messageTextbox.val('')
});
The client originally sent the name but this is no longer going to be the case, the name is stored by the server so we're going to remove this as a required property from createMessage, we're just going to be sending the text across.
socket.emit('createMessage', {
text: messageTextbox.val('')
}, function() {
messageTextbox.val('')
});
Now with this in place we can modify the event listener over inside of server.js. Inside server.js, createMessage takes those two properties and it stuffs them right in to generateMessage. Instead, we're going to find the user using users.getUser and we're going to do something with it.
Right in createMessage we can go ahead and delete our console.log statement for createMessage, and we're going to make a variable user, setting it equal to users.getUser. This is the method we created in users.js, getUser, which takes the id parameter. We can pass in the ID socket.id like this:
socket.on('createMessage', (message, callback) => {
var user = users.getUser(socket.id);
io.emit('newMessage', generateMessage(message.from, message.text));
callback();
});
Now we can do something with user. We only want to do something if a user actually exists, which means that we're going to check if the user exists using if statement, and we're also going to make sure that the text that got passed along was a real string, using, after &&, isRealString. We'll then pass in message.text:
socket.on('createMessage', (message, callback) => {
var user = users.getUser(socket.io);
if(user && isRealString(message.text)){
}
io.emit('newMessage', generateMessage(message.from, message.text));
callback();
});
This means if someone tries to send across an empty message or just a bunch of spaces, it's not going to get sent to everybody else. Now inside the if statement, all we're going to do is actually emit the message. We know it's valid so we do want to emit something, and we're going to take io.emit line, cut it out, and paste it in if statement:
if(user && isRealString(message.text)){
io.emit('newMessage', generateMessage(message.from, message.text));
}
Now currently the io.emit line emits to everybody, not just the room that user is connected to, but we also use message.from. We really want to use the name property on user. We're now going to make those two changes, emit this event just to the room the user is connected to, and make sure to provide their name as opposed to message.from.