Search code examples
javascriptnode.jsmattermost

How do i optimise multiple require() call?


I'm making a bot for the mattermost server of my company (like a discord bot), and for my bot commands, I created one file per command.

The idea is that to send a command, the user must send a message like "!giveChannelPerms arg1 arg 2 ...". The bot will parse the message to identify the command (in this case !giveChannelPerms) and execute the code related to the command.

The problem is that for each command, I have to require() the file and make an if {} else if {} else if {} ... to find the command, as you can see with the code below.

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, args, db, obj);
}

This code is good if we only have 2 commands for our bot, but the more commands I create, the more require() and if {} else if {} will be big.

Isn't there a more "optimized" way to do what I'm trying to do? I had thought of doing something like C function pointers but I have no idea how to do it.


Solution

  • If you want less require and reduce if elses, I recommend you to create a file importing your commands and returning an associated map

    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
    

    Then you will be able to import it only once and use it without conditions in your file :

    // 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);