server/src/services/chatService.ts

47 lines
1.5 KiB
TypeScript

import type { UUID } from '#application/types'
import { BaseService } from '#application/base/baseService'
import { Chat } from '#entities/chat'
import SocketManager from '#managers/socketManager'
import CharacterRepository from '#repositories/characterRepository'
import MapRepository from '#repositories/mapRepository'
class ChatService extends BaseService {
async sendMapMessage(characterId: UUID, mapId: UUID, message: string): Promise<boolean> {
try {
const characterRepository = new CharacterRepository()
const mapRepository = new MapRepository()
const character = await characterRepository.getById(characterId)
if (!character) return false
const map = await mapRepository.getById(mapId)
if (!map) return false
const chat = new Chat()
await chat.setCharacter(character).setMap(map).setMessage(message).save()
const io = SocketManager.getIO()
io.to(mapId).emit('chat:message', chat)
return true
} catch (error: any) {
this.logger.error(`Failed to save chat message: ${error instanceof Error ? error.message : String(error)}`)
return false
}
}
public isCommand(message: string, command?: string) {
if (command) {
return message === `/${command}` || message.startsWith(`/${command} `)
}
return message.startsWith('/')
}
public getArgs(command: string, message: string): string[] | undefined {
if (!this.isCommand(message, command)) return
return message.slice(`/${command} `.length).split(' ')
}
}
export default new ChatService()