Javax.tech
Javax.tech

Reputation: 55

Node.JS Firebase Cloud Function - HTTP Request - Return JSON response to client

I am writing a firebase cloud function to connect to an external database upon HTTP trigger.

This function will do the following:

  1. User submits account number and zipcode
  2. Cloud function is triggered
  3. Account number is appended to URL in request and the external database returns account number and zipcode.

I need to return the response body back to the client.

var functions = require('firebase-functions');
var request = require('request');

exports.account_verification = functions.https.onCall((data, context) => {
    console.log("Data: " + data.text);
    console.log("Context: " + context)

    var options = {
        'method': 'GET',
        'url': '**REDACTED**' + JSON.parse(data.text).customerno,
        'headers': {
        }
    };


     request(options, function (error, response) {
        if (error) throw new Error(error);
        console.log("RESPONSE BODY: ", JSON.parse(response.body).firebase_accounts);
        console.log("Data Submitted: ", data.text);
        console.log("Account Submitted: ", JSON.parse(data.text).customerno);
        console.log("Zip Submitted: ", JSON.parse(data.text).zipcode);

        //data returned from external database
        //Example: firebase_accounts:[{"customerno" : "Example Customer", "zipcode" : "Example Zip Code"}]


        var response_returned = JSON.parse(response.body).firebase_accounts;
         console.log("Data Returned -- Parsed: ", response_returned);
        //Example: [{"customerno" : "Example Customer", "zipcode": "Example Zip Code"}]

 //Response Body available here but will not return to client

    });

//Return to client will work here but cannot access response data

});

Upvotes: 1

Views: 2193

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

Since you're performing an asynchronous request, you'll need to make sure that Cloud Functions waits for that result. This is sometimes referred to as bubbling up the result.

It's easiest when you use promises, but since you're using the request module, that isn't available in there. Instead you can create your own promise, like this:

var functions = require('firebase-functions');
var request = require('request');

exports.account_verification = functions.https.onCall((data, context) => {
    var options = {
        'method': 'GET',
        'url': '**REDACTED**' + JSON.parse(data.text).customerno,
        'headers': {
        }
    };

    return new Promise(function(resolve, reject) {
      request(options, function (error, response) {
        if (error) reject(error);

        var response_returned = JSON.parse(response.body).firebase_accounts;

        resolve(response_returned);
      });
    })
});

Upvotes: 2

Related Questions