refactor(#35): Update room to use partykit

This commit is contained in:
Josh Creek
2024-11-07 20:04:10 +00:00
parent 9347f4fb96
commit 3ffd948346
+18 -19
View File
@@ -1,5 +1,5 @@
import { WebSocket } from 'ws'; import type * as Party from 'partykit/server';
import { User } from './User'; import { User } from './User.js';
class CardSet { class CardSet {
name: string; name: string;
@@ -27,7 +27,7 @@ export const cardSets: Array<CardSet> = [
export class Room { export class Room {
id: string; id: string;
cardSet: CardSet; cardSet: CardSet;
users: Map<WebSocket, User>; users: Map<Party.Connection, User>;
constructor(id: string, cardSetName: string) { constructor(id: string, cardSetName: string) {
this.id = id; this.id = id;
@@ -41,45 +41,44 @@ export class Room {
this.users = new Map(); this.users = new Map();
} }
addUser(ws: WebSocket, user: User) { addUser(connection: Party.Connection, user: User) {
this.users.set(ws, user); this.users.set(connection, user);
} }
removeUser(ws: WebSocket) { removeUser(connection: Party.Connection) {
this.users.delete(ws); this.users.delete(connection);
} }
getUsers() { getUsers() {
return Array.from(this.users.values()); return Array.from(this.users.values());
} }
getUserByWebSocket(ws: WebSocket) { getUserByConnection(connection: Party.Connection): User | undefined {
return this.users.get(ws); return this.users.get(connection);
} }
getWebSocketByUser(user: User): WebSocket | null { getConnectionByUser(user: User): Party.Connection | null {
for (const [ws, u] of this.users) { for (const [connection, u] of this.users) {
if (u === user) { if (u === user) {
return ws; return connection;
} }
} }
return null; return null;
} }
getWebSocketByUserId(userId: String): WebSocket | null { getConnectionByUserId(userId: string): Party.Connection | null {
for (const [ws, u] of this.users) { for (const [connection, u] of this.users) {
if (u.userId === userId) { if (u.userId === userId) {
return ws; return connection;
} }
} }
return null; return null;
} }
broadcast(message: any) { broadcast(message: any) {
this.users.forEach((user, client) => { const messageString = JSON.stringify(message);
if (client.readyState === WebSocket.OPEN) { this.users.forEach((user, connection) => {
client.send(JSON.stringify(message)); connection.send(messageString);
}
}); });
} }