We need to import the isRealString function first before we can actually validate those two properties. We can make a const just below the generateMessage constant and use ES6 destructuring to grab isRealString, and we're going to grab it using require. We require a local file ./. It's in that utils directory and the file name is validation, just like this:
const {generateMessage, generateLocationMessage} = require('./utils/message');
const {isRealString} = require('./utils/validation');
Now we can call isRealString inside join; that's exactly what we're going to do. We're going to check if either of them are not real strings. If one or more are not real strings, we're going to call the callback passing in the error. We'll add if (params.name) as the first one and pass that into isRealString(params.name):
socket.on('join', (params, callback) => {
if(isRealString(params.name))
});
Now we want to check if it's not a real string. So we're going to flip that, or (||), and then we're going to check if the other property, the room name, is not a real string. Now inside the query string, the room name property is called room. So if it's not isRealString passing in the correct value params.room, then that's going to be an error too:
socket.on('join', (params, callback) => {
if(!isRealString(params.name) || !isRealString(params.room))
});
Next, we can handle that error by adding error handler function. For this, I'm going to do is call the callback with a little string message, Name and room name are required:
socket.on('join', (params, callback) => {
if(!isRealString(params.name) || !isRealString(params.room)) {
callback('Name and room name are required.');
}
});
Now if that's not the case we do still want to call the callback but we don't want to pass any arguments in:
socket.on('join', (params, callback) => {
if(!isRealString(params.name) || !isRealString(params.room)) {
callback('Name and room name are required.');
}
callback();
});
Because remember that first argument we set that up to be the error argument in chat.js, and if both things are valid, we do not want to pass any errors back. Over inside server.js, we now have some pretty basic validation set up, and before we actually do anything in here, which is going to be in the upcoming section.