forked from render-examples/bun-docker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.ts
More file actions
73 lines (54 loc) · 2.08 KB
/
app.ts
File metadata and controls
73 lines (54 loc) · 2.08 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { onPlayerEnter } from "./start/onPlayerEnter";
const NODE_ENV = process.env.NODE_ENV ?? "development";
let onlinePlayers: Record<string, string>[] = [];
const chatRoom = "chatRoom";
const server = Bun.serve<{ username: string; playerName: string }>({
fetch(req, server) {
const { searchParams } = new URL(req.url);
const username = searchParams.get("username");
const playerName = searchParams.get("playername");
const success = server.upgrade(req, { data: { username, playerName } });
if (success) return undefined;
return new Response("onlinerikken.nl websocket server");
},
websocket: {
publishToSelf: true,
open(ws) {
ws.subscribe(chatRoom);
const msg = `${ws.data.playerName} (${ws.data.username}) komt de chat binnen`;
ws.publish(chatRoom, msg);
const gameState = onPlayerEnter(ws.data);
ws.publish(chatRoom, `[gameState] ${JSON.stringify(gameState)}`);
// console.log(`[${NODE_ENV}] ${msg}`);
onlinePlayers.push({
playerName: ws.data.playerName,
username: ws.data.username,
});
},
message(ws, message) {
// the server re-broadcasts incoming messages to everyone
const chatMessage = `[chat] ${ws.data.playerName} (${ws.data.username}): ${message}`;
ws.publish(chatRoom, chatMessage);
// Log if the message is not a ping heartbeat
if (message !== "[ping]") {
console.log(`[${NODE_ENV}] ${chatMessage}`);
}
ws.publish(
chatRoom,
`[onlinePlayers] (${onlinePlayers.length}): ${onlinePlayers
.map((player) => `${player.playerName} (${player.username})`)
.join(", ")}`
);
},
close(ws) {
const msg = `${ws.data.playerName} (${ws.data.username}) heeft de chat verlaten`;
ws.publish(chatRoom, msg);
// console.log(`[${NODE_ENV}] ${msg}`);
ws.unsubscribe(chatRoom);
onlinePlayers = onlinePlayers.filter(
(player) => player.username !== ws.data.username
);
},
},
});
console.log(`[${NODE_ENV}] Listening on ${server.hostname}:${server.port}`);