Search code examples
typescriptfirebasecode-organization

typescript manage REST calls and callbacks


I am using google firebase functions with typescript. I have a basic question around better code management. Currently my code looks like below:

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
      }

As you can see above this will be too hard to manage everything in a single function. So how do organize this code so that each of the rest call is a separate function called from above based on if-else.


Solution

  • You can put the code inside the IF block inside a function.

    Ex:

    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
    }