1
0
forked from noxious/server

68 lines
2.2 KiB
TypeScript

import { ZodError } from 'zod'
import { BaseEvent } from '#application/base/baseEvent'
import { ZCharacterCreate } from '#application/zodTypes'
import { Character } from '#entities/character'
import CharacterRepository from '#repositories/characterRepository'
import UserRepository from '#repositories/userRepository'
import ZoneRepository from '#repositories/zoneRepository'
export default class CharacterCreateEvent extends BaseEvent {
public listen(): void {
this.socket.on('character:create', this.handleEvent.bind(this))
}
private async handleEvent(data: any): Promise<any> {
// zod validate
try {
data = ZCharacterCreate.parse(data)
const user = await UserRepository.getById(this.socket.userId!)
if (!user) {
return this.socket.emit('notification', { message: 'User not found' })
}
// Check if character name already exists
const characterExists = await CharacterRepository.getByName(data.name)
if (characterExists) {
return this.socket.emit('notification', { message: 'Character name already exists' })
}
let characters: Character[] = await CharacterRepository.getByUserId(user.getId())
if (characters.length >= 4) {
return this.socket.emit('notification', { message: 'You can only have 4 characters' })
}
// @TODO: Change to default location
const zone = await ZoneRepository.getFirst()
const newCharacter = new Character()
await newCharacter
.setName(data.name)
.setUser(user)
.setZone(zone!)
.save()
if (!newCharacter) {
return this.socket.emit('notification', { message: 'Failed to create character. Please try again (later).' })
}
characters = [...characters, newCharacter]
this.socket.emit('character:create:success')
this.socket.emit('character:list', characters)
this.logger.info('character:create success')
} catch (error: any) {
this.logger.error(`character:create error: ${error.message}`)
if (error instanceof ZodError) {
return this.socket.emit('notification', { message: error.issues[0].message })
}
return this.socket.emit('notification', { message: 'Could not create character. Please try again (later).' })
}
}
}