forked from noxious/server
50 lines
1.6 KiB
TypeScript
50 lines
1.6 KiB
TypeScript
import { Server } from 'socket.io'
|
|
|
|
import { gameLogger } from '#application/logger'
|
|
import { TSocket } from '#application/types'
|
|
import { Chat } from '#entities/chat'
|
|
import CharacterRepository from '#repositories/characterRepository'
|
|
import ChatRepository from '#repositories/chatRepository'
|
|
import ZoneRepository from '#repositories/zoneRepository'
|
|
|
|
class ChatService {
|
|
async sendZoneMessage(io: Server, socket: TSocket, message: string, characterId: number, zoneId: number): Promise<boolean> {
|
|
try {
|
|
const character = await CharacterRepository.getById(characterId)
|
|
if (!character) return false
|
|
|
|
const zone = await ZoneRepository.getById(zoneId)
|
|
if (!zone) return false
|
|
|
|
const newChat = new Chat()
|
|
|
|
newChat.setCharacter(character).setZone(zone).setMessage(message)
|
|
|
|
await newChat.save()
|
|
|
|
const chat = await ChatRepository.getById(newChat.id)
|
|
if (!chat) return false
|
|
|
|
io.to(zoneId.toString()).emit('chat:message', chat)
|
|
return true
|
|
} catch (error: any) {
|
|
gameLogger.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 ChatService
|