diff --git a/app/durableObjects/ChatRoom.server.ts b/app/durableObjects/ChatRoom.server.ts index 8c468b33..7c84560e 100644 --- a/app/durableObjects/ChatRoom.server.ts +++ b/app/durableObjects/ChatRoom.server.ts @@ -49,6 +49,7 @@ export class ChatRoom extends Server { connection: Connection, ctx: ConnectionContext ): Promise { + await this.cleanupOldConnections() // let's start the periodic alarm if it's not already started if (!(await this.ctx.storage.getAlarm())) { // start the alarm to broadcast state every 30 seconds @@ -72,7 +73,7 @@ export class ChatRoom extends Server { } // store the user's data in storage - await this.ctx.storage.put(`session-${connection.id}`, JSON.stringify(user)) + await this.ctx.storage.put(`session-${connection.id}`, user) await this.broadcastRoomState() } @@ -134,10 +135,7 @@ export class ChatRoom extends Server { break } case 'userUpdate': { - this.ctx.storage.put( - `session-${connection.id}`, - JSON.stringify(data.user) - ) + this.ctx.storage.put(`session-${connection.id}`, data.user) await this.broadcastRoomState() break } @@ -172,14 +170,13 @@ export class ChatRoom extends Server { const otherUser = await this.ctx.storage.get( `session-${data.id}` ) - this.ctx.storage.put(`session-${data.id}`, { + await this.ctx.storage.put(`session-${data.id}`, { ...otherUser!, tracks: { ...otherUser!.tracks, audioEnabled: false, }, }) - // this.sendMessage(otherConnection, { type: 'muteMic', }) @@ -237,9 +234,19 @@ export class ChatRoom extends Server { // this.broadcastState() } + async cleanupOldConnections() { + const connections = [...this.getConnections()] + const sessionsToCleanUp = await this.ctx.storage.list() + connections.forEach((connection) => + sessionsToCleanUp.delete(`session-${connection.id}`) + ) + return Promise.all( + [...sessionsToCleanUp.keys()].map((key) => this.ctx.storage.delete(key)) + ) + } + async alarm(): Promise { - // technically we don't need to broadcast state on an alarm, - // but let's keep it for a while and see if it's useful + await this.cleanupOldConnections() await this.broadcastRoomState() if ([...this.getConnections()].length !== 0) { this.ctx.storage.setAlarm(Date.now() + 30000)