forked from aralroca/chat-with-deno-and-preact
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchat.ts
37 lines (30 loc) · 1005 Bytes
/
chat.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import {
WebSocket,
isWebSocketCloseEvent,
} from "https://deno.land/std/ws/mod.ts";
import { v4 } from "https://deno.land/std/uuid/mod.ts";
import { camelize } from "./camelize.ts";
const users = new Map<string, WebSocket>();
function broadcast(message: string, senderId?: string): void {
if (!message) return;
for (const user of users.values()) {
user.send(senderId ? `[${senderId}]: ${message}` : message);
}
}
export async function chat(ws: WebSocket): Promise<void> {
const userId = v4.generate();
// Register user connection
users.set(userId, ws);
broadcast(`> User with the id ${userId} is connected`);
// Wait for new messages
for await (const event of ws) {
const message = camelize(typeof event === "string" ? event : "");
broadcast(message, userId);
// Unregister user conection
if (!message && isWebSocketCloseEvent(event)) {
users.delete(userId);
broadcast(`> User with the id ${userId} is disconnected`);
break;
}
}
}