Chat App With Nest.js + Socket.io in 15 Minutes

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey there today we're going to go ahead and take a look at using sockets uh with nest.js as our back end and we're going to demonstrate this the simple chat app um and which we'll use socket io for on the client side but mainly this is a demonstration to see how the nest js framework fits in to using sockets to start i'm in an empty directory and i'm going to go ahead and generate a new nest project and we can just call it whatever we'd like i'll call it socket back end and like all my tutorials i will leave a link in the description to the github repo if you'd like to follow along so once the project is finished initializing we can go ahead and cd into it and we're going to go ahead and install a few dependencies so with your package manager just go ahead and add uh nest js web sockets and then sgs platform socket.io once that finishes we'll also go ahead and add the types for socket.io so if you're using yarn that looks like this here yarn add dash d for dev dependency and then once we have the types we can go ahead and clear out our output and start up the server in the background so i've gone ahead and opened up the project directory in vs code and the first thing we're going to go do here is and create the file that will be responsible for hosting our our socket logic so i'm going to go ahead and call this chat dot gateway and a gateway is an sjs's abstraction of sockets so they call them gateways and we'll see a little bit more of this in a second here so let's go ahead and actually export the class called chat gateway and importantly to tell nasjs that this is a socket implementation we need to decorate it with websocket gateway and we import that from sjs websockets and there's a couple other things we can include here if you'd like to we can specify a port number that this gateway should be running on if you want it to be running on a different port then what the next gs server runs on in default which is port 3000 so if we wanted to we could specify port 80 for example and another thing we can specify here as well is if you're familiar with socket i o we could specify a name space for just this gateway and all that does is it separates out this gateway from other ones and so all messages you send and receive with the client in this gateway are only going to be sent in this particular name space so on the client side we can join a particular namespace and only get messages for that namespace but for this example we only have one gateway so we will just keep things simple so now that we've set up the gateway we also need to go ahead and tell masjs about it so to do that we will add it to the providers array here so add the chat gateway we just created and import it above now in the chat gateway this is where we're going to add all of the event handlers for an incoming socket message so in our example for our chat application we are going to have to handle incoming messages we're going to want to broadcast them to all listeners of this gateway so that our chat you know has a flow to it to do this we'll create a new function here called handle message which will simply handle an incoming stock message and send it back out so we need to decorate this with a decorator called subscribe message from an sjs websocket and then we provided a string which is the name of the message that we're listening for from the client so the name the client sends in this case we will call it message we could call anything but this is a chat message so it makes sense to call it message um and then as the parameter here we are going to extract the message body and notice we have another decorator here so this message is going to be a type string and we're going to return void so what this decorator does is it just extracts out the message from the data payload that's coming in if we prefer to not use decorators here we can also use this form where we get the client and then the data this works just as well so this way we'd have access to the client and can easily um use methods on that but in our case we're really only concerned with the message body here we don't need access to the client and this will just make things cleaner because we get direct access to the message without having to extract it from the data payload now when we get an incoming message if we only wanted to send it to other people that are subscribed to this gateway we would take that client and emit a message on it but in our case when we have a message that gets sent to our gateway we want to broadcast it to everyone on the server including the person that sent it so in order to do this we need to get access to the server and to do that we can declare a class variable here called server and decorate it with websocket server and sjs will populate this with the server for the gateway so now if we come back into our function body we can call this.server.emit and this is going to emit a message to everyone on the server including the person that sent this message which will be important for our client-side implementation later so we're going to emit a message and this is the name of it the name of the event we're emitting it's messed and all we're going to do is just pass the one that came in and send it back to the server so a client sends a message and we're immediately broadcasting it to everyone on the server and that's really it this is how simple it is to implement sockets on the back end now let's go ahead and set up our client side so we can test this out so to test out our websocket implementation i'll create a new folder in our project called socket client which will be our client implementation so in here i'll just create an index.html so i've gone ahead and added some basic html here all this is just boilerplate but there are a couple of important things we're doing down here importing the socket io library from a cdn so we get access to it and we're also importing a script called chat socket which we'll go ahead and create this script is what's going to actually use socket io and talk to our backend a couple other things here is we're just creating two divs one of which with an id of messages is just going to hold all the messages we receive and the second div simply holds an input field with a button and that button has a click listener called handle submit new message which we are going to set up in our chat socket so in chat socket the first thing we're going to go ahead and do is create our new socket and we get access to io from the cdn we've imported earlier in the html file now io constructors here function takes the url for your websocket backend and in this case our nestgs server is running on localhost port 3000 and notice here this is where we would have taken advantage of that port earlier in our back end if we wanted to specify a different port than what the server is running on we could have but we are just running the i o connection to our nest js server a couple other things we're going to do here first of which we will get access to the message and if you remember correctly a message is just the input field that the user types a new message in and then we'll also get access to the messages div or list rather so you'll get element by id messages so next let's go ahead and set up our handle submit new message function here so handle submit new message it's just going to be a function it doesn't take any parameters and all it's going to do is it's going to call socket.emit and now we specify the name of this message so that when we submit it to our gateway it will pick up into this function handler so it has to match the name we specified here in subscribe message so make sure we type in message here and now we specify the data that we're going to send now this data is what an sjs extracts here in the message body with the data key so it's going to extract the message body which is simply just the data property here and we are going to pass in message.value which simply looks at the input field we have here and extracts the current value of it and then emits it to our server now we need to set up a way to listen to incoming messages and populate them on our page so to do that we will call socket.on and we're going to listen for the event called message because remember the server is emitting the message event as well so on the client side if we want to listen to it we pass in a callback function to execute when we get a new message and we're just going to destructure that property we get back here to get the data from it the data payload we're going to go ahead and need to add it to our document our list of messages so that our chat history is maintained so to do that we'll create a new function called handle new message and handle new message is going to take in a message and what it's going to do is it's going to call messages.appendchild which is simply going to add a new html node to our unordered list of messages so we want to insert a new list item every time we get a new message so we're going to append a new node here and as we're trying to keep our code clean and make sure our functions only do one thing we'll create a new function called uh build new message which will be responsible for actually building the htl html element so it's going to take in the message and we'll go ahead and create the new list item here click on documents i'll create element and then we're going to call a pen child on the list item and we will add a create text node here which allows us to pass in the message text to create a text node so that our list item has the text inside of it and now we can return the list item from this and in messages.pen child all we have to do now is call build new message with a message password finally back in our socket event handler we just need to call handle new message and pass in the data so now if we save we can go ahead and open up or index the html file so i've gone ahead and opened our index.html file i'm going to open up the dev tools here so we can see if we have any errors no errors which is great so we can see our input field here with a submit button and we can type in text here and we can notice that as we send text it gets appended to our listed messages so this is great to see because it means that the client that sends the message is also receiving it from the server and it's pending now in order to see the chat room in action we'll have actually go ahead and open up another window here so now we have two instances of the chat room open we refresh this so now if we send a message in this window we should expect to see it in this one which is great so you can imagine if we hosting this on a remote server these two clients would be able to chat with each other and interact and see all of the messages between them and obviously this is a very simple example but it really shows the power and simplicity of using sockets with nest js so thanks for watching
Info
Channel: Michael Guay
Views: 12,472
Rating: undefined out of 5
Keywords:
Id: 7xpLYk4q0Sg
Channel Id: undefined
Length: 13min 27sec (807 seconds)
Published: Sat Mar 27 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.