Files
server/src/services/chatService.ts
2025-02-12 00:12:26 +01:00

48 lines
1.6 KiB
TypeScript

import type { UUID } from'@/application/types'
import { BaseService } from'@/application/base/baseService'
import { SocketEvent } from'@/application/enums'
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(SocketEvent.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()