server/src/events/zone/characterJoin.ts
2024-12-28 22:12:59 +01:00

63 lines
1.9 KiB
TypeScript

import { BaseEvent } from '#application/base/baseEvent'
import { Zone } from '#entities/zone'
import ZoneManager from '#managers/zoneManager'
import zoneManager from '#managers/zoneManager'
import zoneCharacter from '#models/zoneCharacter'
import CharacterRepository from '#repositories/characterRepository'
interface IResponse {
zone: Zone
characters: zoneCharacter[]
}
export default class CharacterJoinEvent extends BaseEvent {
public listen(): void {
this.socket.on('zone:character:join', this.handleEvent.bind(this))
}
private async handleEvent(callback: (response: IResponse) => void): Promise<void> {
try {
if (!this.socket.characterId) {
this.logger.error('zone:character:join error: Zone requested but no character id set')
return
}
const character = await CharacterRepository.getById(this.socket.characterId)
if (!character) {
this.logger.error('zone:character:join error: Character not found')
return
}
const zone = character.zone
if (!zone) {
// @TODO: If zone is not found, spawn back to the start
this.logger.error('zone:character:join error: Zone not found')
return
}
const loadedZone = ZoneManager.getZoneById(zone.id)
if (!loadedZone) {
this.logger.error('zone:character:join error: Loaded zone not found')
return
}
loadedZone.addCharacter(character)
this.socket.join(zone.id.toString())
// Let other clients know of new character
this.io.to(zone.id.toString()).emit('zone:character:join', zoneManager.getCharacterById(character.id))
// Log
this.logger.info(`User ${character.id} joined zone ${zone.id}`)
// Send over zone and characters to socket
callback({ zone, characters: loadedZone.getCharactersInZone() })
} catch (error: any) {
this.logger.error('zone:character:join error: ' + error.message)
this.socket.disconnect()
}
}
}