如何优化多个require调用?

问题描述

我正在为公司最重要的服务器(例如不和谐的bot)制造一个bot,并且对于我的bot命令,我为每个命令创建了一个文件

这个想法是,要发送命令,用户必须发送类似“!giveChannelPerms arg1 arg 2 ...”的消息。该机器人将解析消息以识别命令(在本例中为!giveChannelPerms),并执行与该命令相关的代码

问题在于,对于每个命令,我都必须require()文件并创建一个if {} else if {} else if {} ...才能找到该命令,如下面的代码所示。

const giveChannelPerms = require('../cmd/giveChannelPerms');
const removeChannelPerms = require('../cmd/removeChannelPerms');

[...]

if (cmd == "!giveChannelPerms") {
    giveChannelPerms.giveChannelPerms(post,args,db,obj);
} else if (cmd == "!removeChannelPerms") {
    removeChannelPerms.removeChannelPerms(post,obj);
}

如果我们的机器人只有2条命令,那么这段代码很好,但是我创建的命令越多,require()越多,如果{}则if {}将会很大。

是否有更“优化”的方式来执行我要尝试的操作?我曾想过要做类似C函数指针的事情,但我不知道该怎么做。

解决方法

如果您希望减少需求并减少其他需求,建议您创建一个文件,以导入命令并返回关联的地图

const { giveChannelPerms } = require('../cmd/giveChannelPerms');
const { removeChannelPerms } = require('../cmd/removeChannelPerms');

const cmdMap = new Map();

cmdMap.set('!giveChannelPerms',giveChannelPerms)
cmdMap.set('!removeChannelPerms',removeChannelPerms)

export default cmdMap

那么您将只能导入一次,并且可以在文件中无条件地使用它:

// Imported multiples functions in one require
const commands = require('../cmd/commands');

// Will execute function associated to cmd string without conditions
commands.get(cmd)(post,args,db,obj);
,

https://stackoverflow.com/a/38397640/932256借用尝试:

const commandFiles = {
    giveChannelPerms: require('../cmd/giveChannelPerms'),removeChannelPerms: require('../cmd/removeChannelPerms')
};

const commandList = Object.keys(commandFiles);

if (cmd.match(new RegExp('^!(' + commandList.join('|') + ')$'))) {
    let baseCommand = cmd.replace('!','');
    commandFiles[baseCommand][baseCommand](post,obj);
}

现在您需要做的就是将命令添加到commandFiles对象中。

,

也许类似的东西会起作用

[...]
require('../cmd/giveChannelPerms').then(res => { 
    if (res) {
        res.giveChannelPerms(post,obj);
    } else {
        require('../cmd/removeChannelPerms').then(rslt =>  {
             if (rslt) rslt.removeChannelPerms(post,obj);
        })
    }
});
  
,

我认为您正在寻找以下两种解决方案,希望对您有帮助

  1. 更优雅的方式来管理进口商品- 为此,您可以创建一个索引文件(index.js),该文件将从不同的文件导入所有命令,并从index.js的一个位置导出所有命令
  2. 简化您的if else条件-从您的代码段中,您似乎需要针对每个命令进行评估,因为每个命令执行的代码不同。由于无法逃避,1. One 2. Two A. Alpha B. Beta 3. Three A. Charlie 1. One 2. Two A. Alpha B. Beta 2. Three A. Charlie 为您提供更好的代码可读性
switch-case