Updated several events to new event format

This commit is contained in:
2024-09-22 00:46:17 +02:00
parent 50d13af5d6
commit 81428ea0c2
9 changed files with 298 additions and 203 deletions

View File

@ -5,55 +5,49 @@ import { Character, Zone } from '@prisma/client'
import CharacterManager from '../../managers/characterManager'
import { gameLogger } from '../../utilities/logger'
interface IPayload {
// zoneId: number
}
interface IResponse {
zone: Zone
characters: Character[]
}
/**
* Handle character zone request event
* @param socket
* @param io
*/
export default function (io: Server, socket: TSocket) {
socket.on('zone:character:join', async (callback: (response: IResponse) => void) => {
try {
if (!socket.characterId) return
const character = CharacterManager.getCharacterFromSocket(socket)
export default class CharacterJoinEvent {
constructor(
private readonly io: Server,
private readonly socket: TSocket
) {}
public listen(): void {
this.socket.on('zone:character:join', this.handleCharacterJoin.bind(this))
}
private async handleCharacterJoin(callback: (response: IResponse) => void): Promise<void> {
try {
if (!this.socket.characterId) return
const character = CharacterManager.getCharacterFromSocket(this.socket)
if (!character) return
const zone = await ZoneRepository.getById(character.zoneId)
if (!zone) {
console.log(`---Zone not found.`)
gameLogger.error('zone:character:join error', 'Zone not found')
return
}
if (character?.zoneId) {
socket.leave(character.zoneId.toString())
io.to(character.zoneId.toString()).emit('zone:character:leave', character)
if (character.zoneId) {
this.socket.leave(character.zoneId.toString())
this.io.to(character.zoneId.toString()).emit('zone:character:leave', character)
}
socket.join(zone.id.toString())
this.socket.join(zone.id.toString())
// let other clients know of new character
io.to(zone.id.toString()).emit('zone:character:join', character)
// add character to zone manager
// ZoneManager.addCharacterToZone(zone.id, socket.character as Character)
// CharacterManager.initCharacter(character as ExtendedCharacter)
// ZoneManager.addCharacterToZone(zone.id, socket.character as Character)
this.io.to(zone.id.toString()).emit('zone:character:join', character)
// send over zone and characters to socket
callback({ zone, characters: CharacterManager.getCharactersInZone(zone) })
} catch (error: any) {
gameLogger.error(`Error requesting zone: ${error.message}`)
socket.disconnect()
gameLogger.error('zone:character:join error', error.message)
this.socket.disconnect()
}
})
}
}
}