To generate newMessage, we are going to make a separate file that we load into server.js with a method we call instead of defining the object. Inside the server folder, we'll make a new directory called utils.
Inside utils we'll make a file called message.js. This will store our utility functions related to messaging, and in our case, we'll make a new one called generateMessage. Let's make a variable called generateMessage. This is going to be a function and will take the two arguments I talked about earlier, from and text:
var generateMessage = (from, text) => {
};
It will then return an object just like the objects we pass in as the second argument to emit in server.js. Now all we need to do is return an object, specifying from as the from argument, text as the text argument, and createdAt, which is going to get generated by calling a new Date and calling its getTime method:
var generateMessage = (from, text) => {
return {
from,
text,
createdAt: new Date().getTime()
};
};
With this in place our utility function is now done. All we need to do is export it down below, module.exports. We'll set that equal to an object that has a generateMessage property equal to the generateMessage variable we have defined:
var generateMessage = (from, text) => {
return {
from,
text,
createdAt: new Date().getTime()
};
};
module.exports = {generateMessage};
We'll eventually be able to integrate this into server.js, but before we do that let's go ahead and write some test cases to make sure it works as expected. This means we will need to install Mocha, and we'll also need to install the Expect assertion library. Then we'll set up our package.json scripts and write the test case.