简体   繁体   中英

I want to modualrise code using javascript

I have one file in which there is lot of code in one function. Say that function name is MessageHandler and in that function there is lot of if else condition and code to be executed after condition is true. The problem is i want to modularised that code using javascript so that it would be maintainable and also it would be easy to find bugs. May be creating different files for every logic.What is the best approach

Part of the Code:

if (userMessage == "/start" && event.channel == "ibc") {
        quickReplies.content.text = metaData.introduction.english;
        quickReplies.msgid = "afterIntro";
        quickReplies.options = metaData.language.english;

        context.sendResponse(JSON.stringify(quickReplies));//First introduction message is sent in english language.

    }

        else if (userMessage == "hi" || userMessage == "hello" || userMessage == "help" || userMessage == "hii" || userMessage == "hey" || userMessage == "wassup") {
        // add filipino and gujarati condition....
        if (context.simpledb.roomleveldata.preferredLang == "hindi") {
            quickReplies.content.text = metaData.introduction.hindi;
            quickReplies.options = metaData.language.hindi;
        } 

    else if(context.simpledb.roomleveldata.preferredLang=="gujarati"){

                quickReplies.content.text = metaData.introduction.gujarati;
            quickReplies.options = metaData.language.gujarati
        }
            else if(context.simpledb.roomleveldata.preferredLang=="filipino"){

                quickReplies.content.text = metaData.introduction.filipino;
            quickReplies.options = metaData.language.filipino;
        }


        else {
            quickReplies.content.text = metaData.introduction.english;
            quickReplies.options = metaData.language.english;
        }
        quickReplies.msgid = "afterIntro";

        context.sendResponse(JSON.stringify(quickReplies));


    } else if (event.messageobj.refmsgid == "afterIntro" || (userMessage.indexOf("change category") > -1) || (userMessage.indexOf("श्रेणी बदलें") > -1) ||(userMessage.indexOf("કેટેગરી બદ") > -1) ||(userMessage.indexOf("baguhin ang kategorya") > -1)) {
        if (userMessage == "अंग्रेजी" || userMessage == "english" || userMessage == "ઇંગલિશ" ||userMessage=="ingles")
        {
            context.simpledb.roomleveldata.preferredLang = "english";
            context.console.log("Enter into english section");
            // context.simpledb.roomleveldata.optinFlag = '1';
            userMessage = "english";
        } else if (userMessage == "हिंदी" || userMessage == "hindi" || userMessage == "હિન્દી") 
        {
            context.simpledb.roomleveldata.preferredLang = "hindi";
            // context.simpledb.roomleveldata.optinFlag = '1';
            userMessage = "hindi";
        } else if (userMessage == "गुजराती" || userMessage == "gujarati" || userMessage == "ગુજરાતી"){
            context.simpledb.roomleveldata.preferredLang = "gujarati";
            // context.simpledb.roomleveldata.optinFlag = '1'ફિલિપિનો"
            userMessage = "gujarati";
        } else if (userMessage == "filipino" || userMessage == "फिलिपिनो" || userMessage == "ફિલિપિનો") {
            context.simpledb.roomleveldata.preferredLang = "filipino";
            // context.simpledb.roomleveldata.optinFlag = '1'ફિલિપિનો"

            userMessage = "filipino";
        } else {
            userMessage = context.simpledb.roomleveldata.preferredLang
            // context.simpledb.roomleveldata.optinFlag = '1';
        }
        var languageArray = metaData.language.english;
        for (var i = 0; i < languageArray.length; i++) {
            if (userMessage == metaData.language.english[i]) {
                console.log("language"+metaData.language.english[i]);
                quickReplies.content.text = metaData.introMessage[metaData.language.english[i].toString()];
                quickReplies.msgid = "afterLanguage";
                quickReplies.options = metaData[metaData.language.english[i].toString()];
                context.sendResponse(JSON.stringify(quickReplies));///Intro message and categories to choose from.
            }
        }
    } else if (userMessage == 'change language' || (userMessage.indexOf('hindi') > -1) || (userMessage.indexOf('english') > -1) || (userMessage.indexOf('gujarati') > -1)|| (userMessage.indexOf('filipino') > -1)) {
        var currentLanguage = context.simpledb.roomleveldata.preferredLang;
        quickReplies.content.text = metaData.introduction[currentLanguage + 'language'];
        quickReplies.options = metaData.language[currentLanguage];
        quickReplies.msgid = "afterIntro";
        context.console.log("currentLanguage=======" + currentLanguage);
        context.sendResponse(JSON.stringify(quickReplies));////give option to change the language in preferred language with prefereed messsage describing what to do.
    } else if (userMessage == 'powered by gupshup') {
        context.sendResponse("This chatbot is powered by gupshup.io- world's leading filipinoform." +
            " Join the bot bandwagon along with- VentureBeat, Infosys, Sage, ICICI etc. " +
            "to build captivating and powerful experiences for your users.");
    } else if (event.messageobj.refmsgid == "afterLanguage")
    // }else if(context.simpledb.roomleveldata.optinFlag == '1')
    {
        context.simpledb.roomleveldata.optinFlag = '0';
        var quoteType;
        var items = [];
        var currentLanguage = context.simpledb.roomleveldata.preferredLang;
        for (var i = 0; i < metaData[currentLanguage].length; i++) //["Motivational", "Love", "Life", "Funny", "Positive"]
        {
            quoteType = metaData[currentLanguage][i].toLowerCase().toString(); //["Motivational", "Love", "Life", "Funny", "Positive"]
            context.console.log(userMessage + "--------quoteType----" + quoteType);
            if (userMessage == quoteType) {
                context.console.log("Cureeeeentttt quote typeeeee"+userMessage);
                catalogue.msgid = quoteType;
                // if(currentLanguage == "filipino")
                // {
                //  quoteType = metaData['english'][i+1].toLowerCase().toString(); //
                // }else
                // {
                    quoteType = metaData['english'][i].toLowerCase().toString(); // 
                // }

                    quoteType=quoteType.replace(/ /g,"_");
                    context.console.log("QQQQQQQQQQQQUOTEEEEEEE"+quoteType);
                var imageURL = context.simpledb.botleveldata[quoteType + 'JSONObj'];
                context.console.log("imageURL--------" + imageURL);
                if(JSON.stringify(imageURL).indexOf(currentLanguage)>-1)
                {
                    for (var j = 0; j < imageURL.length; j++) // {["ImageURL:'',Language:''"]}
                    {
                        context.console.log(imageURL[j]['Language'].toString() + "---------currentLanguage" + currentLanguage);
                            if (imageURL[j]['Language'].toString() == currentLanguage) {
                                context.console.log("imageURL[j]['Language'].toString()==============" + imageURL[j]['Language'].toString())
                                if (j % 9 == 0 && j != 0) {
                                    items.push({
                                        "title": "For More Quotes",
                                        "imgurl": "https://s3.amazonaws.com/gs-bot-images/Quote-Mister/search.jpg",
                                        "options": [{
                                            "type": "text",
                                            "title": "Keep Looking"
                                        }]
                                    });
                                    break;
                                } else {
                                    items.push({
                                        "title": metaData.carousal[currentLanguage + "_title"],
                                        "imgurl": imageURL[j]['Image URL'].toString(),
                                        "options": [{
                                            "type": "url",
                                            "title": "Preview",
                                            "url": imageURL[j]['Image URL'].toString()
                                        }, {
                                            "type": "url",
                                            "title": metaData.carousal[currentLanguage + '_button_text'][0],
                                            "url": "https://www.gupshup.io/developer/bot/devNewImageQuotes/share?text=" + imageURL[j]['Image URL'].toString(),
                                            "webview_height_ratio": "compact"
                                        }, {
                                            "type": "url",
                                            "title": metaData.carousal[currentLanguage + '_button_text'][1],
                                            "url": "https://www.facebook.com/sharer/sharer.php?u=" + imageURL[j]['Image URL'].toString(),
                                            "webview_height_ratio": "compact"
                                        }]
                                    });
                                    context.simpledb.roomleveldata['index'] = j;
                                }
                            }
                    }

You could use patterns like a module. Do your code more legible, like a history, put each piece of code in one function and keep these functions in files where make sense be there, and when you need help calling as follow:

 doActionOne() doOtherAction(params) isValidAction() // use is to validate true/false 

Here has a famous Design Pattern Book . :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM