|
| 1 | +import { EventEmitter } from '@dumber-dungeons/shared/src/event.emitter'; |
| 2 | +import { |
| 3 | + type Session, |
| 4 | + SessionStatus, |
| 5 | +} from '@dumber-dungeons/shared/src/api/session'; |
| 6 | +import { type Participant } from '@dumber-dungeons/shared/src/api/participant'; |
| 7 | +import { |
| 8 | + type ParticipantChangeEvent, |
| 9 | + type ParticipantJoinEvent, |
| 10 | + type ParticipantLeaveEvent, |
| 11 | + type SocketEventMap, |
| 12 | +} from '@dumber-dungeons/shared/src/api/socket.events'; |
| 13 | +import type { Socket } from 'socket.io-client'; |
| 14 | + |
| 15 | +export class DungeonClient { |
| 16 | + public readonly onParticipantJoin = new EventEmitter<ParticipantJoinEvent>(); |
| 17 | + public readonly onParticipantChange = |
| 18 | + new EventEmitter<ParticipantChangeEvent>(); |
| 19 | + public readonly onParticipantLeave = |
| 20 | + new EventEmitter<ParticipantLeaveEvent>(); |
| 21 | + private session: Session; |
| 22 | + private socket: Socket<SocketEventMap>; |
| 23 | + |
| 24 | + constructor(socket: Socket) { |
| 25 | + this.socket = socket; |
| 26 | + |
| 27 | + this.session = { |
| 28 | + id: '', |
| 29 | + status: SessionStatus.IN_LOBBY, |
| 30 | + participants: [], |
| 31 | + }; |
| 32 | + |
| 33 | + this.subscribeToSocket(); |
| 34 | + } |
| 35 | + |
| 36 | + public getParticipants(): Array<Participant> { |
| 37 | + return [...this.session.participants]; |
| 38 | + } |
| 39 | + |
| 40 | + private subscribeToSocket(): void { |
| 41 | + this.socket.on('participant/join', (participant: Participant) => { |
| 42 | + this.addParticipant(participant); |
| 43 | + this.onParticipantJoin.emit({ participant }); |
| 44 | + }); |
| 45 | + this.socket.on('participant/update', (participant: Participant) => { |
| 46 | + this.updateParticipant(participant); |
| 47 | + this.onParticipantChange.emit({ participant }); |
| 48 | + }); |
| 49 | + this.socket.on('participant/leave', (participant: Participant) => { |
| 50 | + this.removeParticipant(participant); |
| 51 | + this.onParticipantLeave.emit({ participant }); |
| 52 | + }); |
| 53 | + } |
| 54 | + |
| 55 | + private addParticipant(participant: Participant): void { |
| 56 | + this.session.participants.push(participant); |
| 57 | + } |
| 58 | + |
| 59 | + private removeParticipant(participant: Participant): void { |
| 60 | + this.session.participants = this.session.participants.filter( |
| 61 | + (p) => p.id != participant.id |
| 62 | + ); |
| 63 | + } |
| 64 | + |
| 65 | + private updateParticipant(participant: Participant): void { |
| 66 | + const idx = this.session.participants.findIndex( |
| 67 | + (p) => p.id == participant.id |
| 68 | + ); |
| 69 | + |
| 70 | + if (idx < 0) this.addParticipant(participant); |
| 71 | + else this.session.participants[idx] = participant; |
| 72 | + } |
| 73 | +} |
0 commit comments