32 lines
889 B
TypeScript
Raw Normal View History

import { joinRoom, Room, RoomConfig } from 'trystero'
import memoize from 'fast-memoize'
2022-08-13 12:11:59 -05:00
export class PeerRoom {
2022-08-14 21:49:14 -05:00
private room: Room
2022-08-13 12:11:59 -05:00
private roomConfig: RoomConfig
2022-08-14 21:49:14 -05:00
constructor(config: RoomConfig, roomId: string) {
this.roomConfig = config
this.room = joinRoom(this.roomConfig, roomId)
2022-08-13 12:11:59 -05:00
}
2022-08-14 21:26:50 -05:00
leaveRoom = () => {
2022-08-13 12:11:59 -05:00
if (this.room) {
this.room.leave()
}
}
2022-08-14 17:49:31 -05:00
2022-08-14 21:26:50 -05:00
makeAction = <T>(namespace: string) => {
return this.room.makeAction<T>(namespace)
2022-08-14 17:49:31 -05:00
}
2022-08-13 12:11:59 -05:00
}
// Memoization isn't just a performance optimization here. It is necessary to
// prevent subsequent calls to getPeerRoom from causing a room collision due to
// the amount of time it takes for Trystero rooms to be torn down (which is an
2022-08-17 09:28:22 -05:00
// asynchronous operation that cannot be `await`-ed).
export const getPeerRoom = memoize((config: RoomConfig, roomId: string) => {
return new PeerRoom(config, roomId)
})