You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
50 lines
1.5 KiB
50 lines
1.5 KiB
import { Container, ContainerModule } from "inversify"
|
|
import _logger from "logger/main"
|
|
|
|
const logger = _logger.createNamespace("command")
|
|
|
|
/**
|
|
* 自动加载所有命令模块
|
|
*/
|
|
const commandModules = import.meta.glob("./**/command.{ts,js}", { eager: true })
|
|
|
|
const modules = new ContainerModule(bind => {
|
|
// 自动绑定所有命令类
|
|
Object.values(commandModules).forEach(module => {
|
|
// 由于 module 类型为 unknown,先进行类型断言为包含 default 属性的对象
|
|
const CommandClass = (module as { default: any }).default
|
|
if (CommandClass) {
|
|
const className = CommandClass.name.replace("Command", "")
|
|
logger.debug(`绑定命令类: ${className}Command`)
|
|
if (CommandClass["init"]) {
|
|
CommandClass["init"]()
|
|
}
|
|
bind(className + "Command")
|
|
.to(CommandClass)
|
|
.inSingletonScope()
|
|
}
|
|
})
|
|
})
|
|
|
|
/**
|
|
* 销毁所有命令绑定
|
|
* @param ioc - Inversify 容器实例
|
|
*/
|
|
async function destroyAllCommand(ioc: Container) {
|
|
const allIOC: any[] = []
|
|
Object.values(commandModules).forEach(module => {
|
|
const CommandClass = (module as { default: any }).default
|
|
if (CommandClass) {
|
|
const className = CommandClass.name.replace("Command", "")
|
|
const m = ioc.get(className + "Command") as any
|
|
if (m && m.destroy) {
|
|
allIOC.push(m.destroy())
|
|
}
|
|
}
|
|
})
|
|
await Promise.all(allIOC)
|
|
await ioc.unloadAsync(modules)
|
|
}
|
|
|
|
export { modules, destroyAllCommand }
|
|
export default modules
|
|
|