1
0
forked from noxious/server

Update command manager and commands to OOP

This commit is contained in:
2024-09-30 22:29:58 +02:00
parent 3ec4bc2557
commit 6ac827630a
4 changed files with 68 additions and 46 deletions

View File

@ -3,9 +3,10 @@ import * as fs from 'fs'
import * as path from 'path'
import { Server } from 'socket.io'
import { commandLogger } from '../utilities/logger'
import config from '../utilities/config'
class CommandManager {
private commands: Map<string, Function> = new Map()
private commands: Map<string, any> = new Map()
private rl: readline.Interface
private io: Server | null = null
private rlClosed: boolean = false
@ -40,7 +41,9 @@ class CommandManager {
private async processCommand(command: string): Promise<void> {
const [cmd, ...args] = command.trim().split(' ')
if (this.commands.has(cmd)) {
this.commands.get(cmd)?.(args, this.io as Server)
const CommandClass = this.commands.get(cmd)
const commandInstance = new CommandClass(this.io as Server)
await commandInstance.execute(args)
} else {
this.handleUnknownCommand(cmd)
}
@ -72,24 +75,30 @@ class CommandManager {
private async loadCommand(commandsDir: string, file: string) {
try {
const ext = path.extname(file)
const commandName = path.basename(file, ext)
const extension = config.ENV === 'development' ? '.ts' : '.js'
const commandName = path.basename(file, extension)
const commandPath = path.join(commandsDir, file)
// Use dynamic import
const module = await import(commandPath)
this.registerCommand(commandName, module.default)
if (typeof module.default === 'function') {
this.registerCommand(commandName, module.default)
} else {
commandLogger.warn(`Unrecognized export in ${file}`)
}
} catch (error) {
commandLogger.error(`Failed to load command: ${file}: ${error}`)
}
}
private registerCommand(name: string, command: (args: string[], io: Server) => void) {
private registerCommand(name: string, CommandClass: any) {
if (this.commands.has(name)) {
commandLogger.warn(`Command '${name}' is already registered. Overwriting...`)
}
this.commands.set(name, command)
this.commands.set(name, CommandClass)
commandLogger.info(`Registered command: ${name}`)
}
}
export default new CommandManager()
export default new CommandManager()