handle messages in the chat room
This commit is contained in:
parent
eb696faae0
commit
4570923287
@ -1,7 +1,13 @@
|
|||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import { serveStatic, createBunWebSocket } from "hono/bun";
|
import { serveStatic, createBunWebSocket } from "hono/bun";
|
||||||
import type { ServerWebSocket } from "hono";
|
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 app = new Hono();
|
||||||
const users: string[] = [];
|
const users: string[] = [];
|
||||||
@ -12,16 +18,20 @@ app.get("/chat-socket", upgradeWebSocket((c) => {
|
|||||||
return {
|
return {
|
||||||
onMessage(event, ws) {
|
onMessage(event, ws) {
|
||||||
const data = JSON.parse(event.data);
|
const data = JSON.parse(event.data);
|
||||||
|
|
||||||
if (!chatters.find(c => c.name == data.chatter.name)) {
|
if (!chatters.find(c => c.name == data.chatter.name)) {
|
||||||
chatters.push(data.chatter);
|
chatters.push(data.chatter);
|
||||||
}
|
}
|
||||||
chatRoom.addMessage({
|
|
||||||
|
const message: Message = {
|
||||||
chatter: { data.chatter },
|
chatter: { data.chatter },
|
||||||
message: data.message,
|
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() {
|
onClose() {
|
||||||
console.log("Connection closed.");
|
console.log("Connection closed.");
|
||||||
@ -32,7 +42,6 @@ app.get("/chat-socket", upgradeWebSocket((c) => {
|
|||||||
}
|
}
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
|
||||||
// get the HTML and JS from the static repo
|
// get the HTML and JS from the static repo
|
||||||
app.use("/", serveStatic({ path: "/static/index.html" }));
|
app.use("/", serveStatic({ path: "/static/index.html" }));
|
||||||
app.use("/*", serveStatic({ root: "/static" }));
|
app.use("/*", serveStatic({ root: "/static" }));
|
||||||
|
Loading…
Reference in New Issue
Block a user