代码之家  ›  专栏  ›  技术社区  ›  Vik

typescript管理rest调用和回调

  •  0
  • Vik  · 技术社区  · 7 年前

    我正在使用带有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
          }
    

    正如您在上面所看到的,这将很难在单个函数中管理所有内容。所以如何组织这段代码,使每个rest调用都是基于if else从上面调用的单独函数。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Yayo Arellano    7 年前

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