server/src/services/chatService.ts
2025-01-02 17:31:24 +01:00

46 lines
1.5 KiB
TypeScript

import { Server } from 'socket.io'
import { BaseService } from '#application/base/baseService'
import { TSocket, UUID } from '#application/types'
import { Chat } from '#entities/chat'
import SocketManager from '#managers/socketManager'
import CharacterRepository from '#repositories/characterRepository'
import ChatRepository from '#repositories/chatRepository'
import MapRepository from '#repositories/mapRepository'
class ChatService extends BaseService {
async sendMapMessage(characterId: UUID, mapId: UUID, message: string): Promise<boolean> {
try {
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.split(`/${command} `)[1].split(' ')
}
}
export default new ChatService()