машинопись управлять вызовами REST и обратными вызовами - PullRequest
0 голосов
/ 26 июня 2018

Я использую функции Google Firebase с машинописью. У меня есть основной вопрос по поводу лучшего управления кодом. В настоящее время мой код выглядит следующим образом:

export const on_command_ping = functions.database.ref("commands/ping/{id}").onWrite(async (change, context) => {
    if(instr == '/my-sr'){
        const reoptions = {
            uri: baseUrl + '/serviceRequests',
            headers: {
                'Authorization': "Basic " + btoa(username + ":" + password)
            },
            json:true
        };

        const result = await rp.get(reoptions)
            .then(function(resp){
                console.log("got the response dude:" + JSON.stringify(resp))


                const options = {
                    uri: respUrl, 
                    method: "POST",
                    json: true,
                    body: { "attachments": [{
                                    "fallback": "Sorry failed to get response"}]
                          }
                 }
                 return rp(options);
               }));
     }else  if(instr == '/my-oher-stuff'){
        //another REST call
      }

Как вы можете видеть выше, будет слишком сложно управлять всем в одной функции. Итак, как организовать этот код так, чтобы каждый из остальных вызовов был отдельной функцией, вызываемой сверху, на основе if-else.

1 Ответ

0 голосов
/ 26 июня 2018

Вы можете поместить код внутри блока IF внутри функции.

Пример:

export const on_command_ping = functions.database.ref("commands/ping/{id}").onWrite(async (change, context) => {
    if (instr == '/my-sr') {
        return function1(change, context)
    }
    else if (instr == '/my-oher-stuff') {
        return function2(change, context)
    } 
    else {
        return function3(change, context)
    }

});

function function1(change, context) {
    const reoptions = {
        uri: baseUrl + '/serviceRequests',
        headers: {
            'Authorization': "Basic " + btoa(username + ":" + password)
        },
        json: true
    };

    const result = await
    rp.get(reoptions)
        .then(function (resp) {
            console.log("got the response dude:" + JSON.stringify(resp))


            const options = {
                uri: respUrl,
                method: "POST",
                json: true,
                body: {
                    "attachments": [{
                        "fallback": "Sorry failed to get response"
                    }]
                }
            }
            return rp(options);
        }));
}

function function2(change, context) {
    //Some code here
}

function function3(change, context) {
    //Some code here
}
...