【问题标题】:typescript manage REST calls and callbackstypescript 管理 REST 调用和回调
【发布时间】:2018-06-26 05:41:56
【问题描述】:

我正在使用带有 typescript 的 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 从上面调用的单独函数。

【问题讨论】:

  • 在你的代码中 instr 永远不会被定义。
  • 对不起,我吃了一些与我的问题无关的片段,以保持简短。

标签: typescript firebase code-organization


【解决方案1】:

您可以将代码放在函数内部的 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
}

【讨论】:

    猜你喜欢
    • 2013-10-18
    • 2015-05-04
    • 2018-03-23
    • 2018-02-09
    • 2020-12-26
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多