Skip to content

Commit

Permalink
Clean up old connections and remove stringify for storage
Browse files Browse the repository at this point in the history
  • Loading branch information
third774 committed Aug 15, 2024
1 parent 5b5aef7 commit 70efa1d
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions app/durableObjects/ChatRoom.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export class ChatRoom extends Server<Env> {
}

// 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()
}
Expand Down Expand Up @@ -134,10 +134,7 @@ export class ChatRoom extends Server<Env> {
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
}
Expand Down Expand Up @@ -172,14 +169,13 @@ export class ChatRoom extends Server<Env> {
const otherUser = await this.ctx.storage.get<User>(
`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',
})
Expand Down Expand Up @@ -237,9 +233,17 @@ export class ChatRoom extends Server<Env> {
// this.broadcastState()
}

async cleanupOldConnections() {
const connections = [...this.getConnections()]
const sessionsToCleanUp = await this.ctx.storage.list<User>()
connections.forEach((connection) =>
sessionsToCleanUp.delete(`session-${connection.id}`)
)
return this.ctx.storage.delete([...sessionsToCleanUp.keys()])
}

async alarm(): Promise<void> {
// 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)
Expand Down

0 comments on commit 70efa1d

Please sign in to comment.