import { Hono } from "hono"; import { serveStatic, createBunWebSocket } from "hono/bun"; import type { ServerWebSocket } from "hono"; import { chatRoom, createMessageString, type Message } from "./chat-room.ts"; const app = new Hono(); // Set up the chat socket const { upgradeWebSocket, websocket } = createBunWebSocket(); app.get("/chat-service", upgradeWebSocket((c) => { return { onOpen(_event, ws) { chatRoom.addListener('message-added', function (e) { ws.send(JSON.stringify({ message: e.message.message, chatter: e.message.chatter, timestamp: e.message.timestamp })); }); }, onMessage(event, ws) { const { data } = event; const message = JSON.parse(data); message.timestamp = Date.now() as string; chatRoom.addMessage(message); }, onClose() { console.log("Connection closed."); }, onError(event) { console.error(event); } } })); // set up the username, somehow // set the session for a user app.post("/login", async (c) => { const user = await c.req.parseBody(); let success: boolean = false; if (!users.find((u) => u == user.username)) { users.push(user.username); success = true; } return c.json({ success }); }); // get the HTML and JS from the static repo app.use("/", serveStatic({ path: "/static/index.html" })); app.use("/*", serveStatic({ root: "/static" })); Bun.serve({ fetch: app.fetch, websocket });