From 457092328703b7cc4ec9d1c8b464934e284a75cd Mon Sep 17 00:00:00 2001 From: Dave Smith-Hayes Date: Sun, 29 Sep 2024 22:07:13 -0400 Subject: [PATCH] handle messages in the chat room --- chat-app/src/index.ts | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/chat-app/src/index.ts b/chat-app/src/index.ts index f241dd1..ccc0aee 100644 --- a/chat-app/src/index.ts +++ b/chat-app/src/index.ts @@ -1,7 +1,13 @@ import { Hono } from "hono"; import { serveStatic, createBunWebSocket } from "hono/bun"; import type { ServerWebSocket } from "hono"; -import { chatRoom, chatters } from "./chat-room.ts"; +import { + chatRoom, + createMessageString, + type Chatter, + type Message + +} from "./chat-room.ts"; const app = new Hono(); const users: string[] = []; @@ -12,16 +18,20 @@ app.get("/chat-socket", upgradeWebSocket((c) => { return { onMessage(event, ws) { const data = JSON.parse(event.data); + if (!chatters.find(c => c.name == data.chatter.name)) { chatters.push(data.chatter); } - chatRoom.addMessage({ + + const message: Message = { chatter: { data.chatter }, message: data.message, - timestamp: Date.now() - }); + timestamp: Date.now() as string; + }; - ws.send(JSON.stringify(chatRoom.getMessage().message)); + chatRoom.addMessage(message); + + ws.send(JSON.stringify({ message: createMessageString(message) })); }, onClose() { console.log("Connection closed."); @@ -32,7 +42,6 @@ app.get("/chat-socket", upgradeWebSocket((c) => { } })); - // get the HTML and JS from the static repo app.use("/", serveStatic({ path: "/static/index.html" })); app.use("/*", serveStatic({ root: "/static" }));