-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
91 lines (78 loc) · 2.37 KB
/
server.ts
File metadata and controls
91 lines (78 loc) · 2.37 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import type * as Party from "partykit/server";
interface ConnectedUser {
connectionId: string;
userId: string;
login: string;
}
interface ConnectedUsersMessage {
type: "connected_users";
users: Array<{
id: string;
login: string;
}>;
}
interface UserStatusMessage {
type: "user_status";
action: "connected" | "disconnected";
userId: string;
login: string;
}
export default class Server implements Party.Server {
connectedUsers: Map<string, ConnectedUser> = new Map();
constructor(readonly party: Party.Party) { }
private broadcastConnectedUsers() {
const message: ConnectedUsersMessage = {
type: "connected_users",
users: Array.from(this.connectedUsers.values()).map(u => ({
id: u.userId,
login: u.login
}))
};
this.party.broadcast(JSON.stringify(message));
}
async onConnect(conn: Party.Connection, ctx: Party.ConnectionContext) {
// We'll wait for the github_user message to add the user
}
async onClose(connection: Party.Connection<unknown>): Promise<void> {
const user = this.connectedUsers.get(connection.id);
if (user) {
this.connectedUsers.delete(connection.id);
// Notify everyone about the disconnection
const statusMessage: UserStatusMessage = {
type: "user_status",
action: "disconnected",
userId: user.userId,
login: user.login
};
this.party.broadcast(JSON.stringify(statusMessage));
// Update everyone with the new list of connected users
this.broadcastConnectedUsers();
}
}
onMessage(message: string, sender: Party.Connection) {
try {
const data = JSON.parse(message);
if (data.type === "github_user") {
// Store the user information
this.connectedUsers.set(sender.id, {
connectionId: sender.id,
userId: data.id,
login: data.login
});
// Notify everyone about the new connection
const statusMessage: UserStatusMessage = {
type: "user_status",
action: "connected",
userId: data.id,
login: data.login
};
this.party.broadcast(JSON.stringify(statusMessage));
// Send current connected users to everyone
this.broadcastConnectedUsers();
}
} catch (e) {
console.error("Failed to parse message:", e);
}
}
}
Server satisfies Party.Worker;