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" }));