LLD of chat app using nodejs event
Created on: Aug 15, 2024
Let's create a chat app using nodejs event. Here we will focus on events.
Let's create a chatroom by inheriting from EventEmitter.
const EventEmitter = require("events"); class ChatRoom extends EventEmitter { constructor() { super(); this.users = {}; } join(username) { console.log(`${username} has joined the chat.`); this.users[username] = (sender, message) => { if (sender !== username) { console.log( `${username} received a message from ${sender}: ${message}` ); } }; this.emit("join", username); } sendMessage(sender, recipient, message) { console.log(`${sender} to ${recipient}: ${message}`); this.emit("message", sender, recipient, message); } leave(username) { console.log(`${username} has left the chat.`); this.emit("leave", username); delete this.users[username]; } }
Let's create a object of charroom
const chatRoom = new ChatRoom(); chatRoom.on("join", (username) => { console.log(`Welcome, ${username}!`); }); chatRoom.on("message", (sender, recipient, message) => { const recipientListener = chatRoom.users[recipient]; if (recipientListener) { recipientListener(sender, message); } else { console.log(`User ${recipient} not found.`); } }); chatRoom.on("leave", (username) => { console.log(`Goodbye, ${username}. See you next time!`); });
We have attached listener for join, message, leave event. Now let's run this program
chatRoom.join("Alice"); chatRoom.join("Bob"); chatRoom.join("Charlie"); chatRoom.sendMessage("Alice", "Bob", "Hey Bob, how are you?"); chatRoom.sendMessage("Bob", "Alice", "I'm good, Alice! How about you?"); chatRoom.sendMessage("Alice", "Charlie", "Hi Charlie!"); chatRoom.sendMessage("Charlie", "Alice", "Hello Alice!"); chatRoom.leave("Alice"); chatRoom.leave("Bob"); chatRoom.leave("Charlie");
Output
Alice has joined the chat. Welcome, Alice! Bob has joined the chat. Welcome, Bob! Charlie has joined the chat. Welcome, Charlie! Alice to Bob: Hey Bob, how are you? Bob received a message from Alice: Hey Bob, how are you? Bob to Alice: I'm good, Alice! How about you? Alice received a message from Bob: I'm good, Alice! How about you? Alice to Charlie: Hi Charlie! Charlie received a message from Alice: Hi Charlie! Charlie to Alice: Hello Alice! Alice received a message from Charlie: Hello Alice! Alice has left the chat. Goodbye, Alice. See you next time! Bob has left the chat. Goodbye, Bob. See you next time! Charlie has left the chat. Goodbye, Charlie. See you next time!
In real world application, we will be using websocket to handle connection and db like cassandra which can hold huge amount of data.
You can check code here. github