handle messages in the chat room

This commit is contained in:
Dave Smith-Hayes 2024-09-29 22:07:13 -04:00
parent eb696faae0
commit 4570923287

View File

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