Executing multiple instances of a Firebase cloud function

I am working with a Firebase (Google) cloud function that is structured like this

// Initialize the Auth0 client
var AuthenticationClient = require('auth0').AuthenticationClient;
var auth0 = new AuthenticationClient({
    domain:       'familybank.auth0.com',
    clientID:     'REDACTED'
});

function retrieveAccountBalance(app) {
    console.log('accessToken: ' + app.getUser().accessToken);
    auth0.getProfile(app.getUser().accessToken, function (err, userInfo) {
        if (err) {
            console.error('Error getting userProfile from Auth0: ' + err);
        }
        console.log('getAccountBalance userInfo:' + userInfo)

        let accountOwner = app.getArgument(PARAM_ACCOUNT_OWNER);

        // Query Firestore based on user
        var transactions = db.collection('bank').doc(userInfo.email)
                          .db.collection('accounts').doc(accountOwner)
                          .collection('transactions');
        var accountBalance = transactions.get()
            .then( snapshot => {
                var workingBalance = 0
                snapshot.forEach(doc => {
                    workingbalance = workingbalance + doc.data().amount;
                });

                app.tell(accountOwner + " has a balance of $" + workingBalance)
            })
            .catch(err => {
                console.log('Error getting transactions', err);
                app.tell('I was unable to retrieve your balance at this time.')
            });
    });
}
actionMap.set(INTENT_ACCOUNT_BALANCE, retrieveAccountBalance);
app.handleRequest(actionMap);

Upon execution, I encounter the following logs

https://i.stack.imgur.com/hgtJj.jpg

There seems to be a recurring issue where parts of the function are being executed multiple times and some calls are failing. Interestingly, if I terminate the auth0.getProfile call after logging userInfo, the function works but lacks the necessary userInfo.

Can anyone shed light on why certain parts of this function are running repeatedly and why some calls are unsuccessful?

Answer №1

At line (2), the userInfo variable is undefined due to an error that occurred just before it was logged. The code within the error block does not exit the function, causing it to continue running with an invalid userInfo object.

However, the issue of the callback being called twice – once with a valid userInfo and once with an err – remains unclear. According to the documentation for

AuthenticationClient.getProfile()
, it returns a Promise or undefined. This ambiguity raises the question of whether this dual callback scenario could be triggered by invoking the promise twice.

Considering the promise return, you can achieve similar functionality without a callback by utilizing the following approach:

function checkBalance(service) {
    let user = service.getTarget(PARAM_USER);
    console.log('Token: ' + service.getUser().token);
    var token = service.getUser().token;
  
    auth0.getProfile(token).then(userInfo => {
        console.log('User Info:' + userInfo)

        // Querying firestore based on user
        var transactions = db.collection('bank').doc(userInfo.email)
                          .db.collection('accounts').doc(user)
                          .collection('transactions');
        return transactions.get();
      })

      .then(snapshot => {
        var balance = 0;
        snapshot.forEach(doc => {
          balance += doc.data().amount;
        });

        service.tell(user + " has a balance of $" + balance);
      })

      .catch(error => {
        console.error('Error:', error );
        service.tell('Unable to retrieve your balance at this time.');
      });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Securing routes with passport.js in a MEAN Stack setting

I am facing an issue with securing individual routes in my admin panel using passport.js. The user signup functionality is working fine, and I am able to login successfully. However, the req.isAuthenticated() function always returns false, preventing me fr ...

When the browser requests "element.html," a compiled jade file is served using Express

Within my layout.jade, I have included link imports for regular HTML Polymer elements like this: link(rel="import" href="/bower_components/paper-tabs/paper-tabs.html") After coming across this gist, I decided to write my Polymer elements in jade. However ...

Executing multiple MySQL queries in sequence using Express in a Node.js environment

I've written the code below, which includes a post request that runs 2 queries along with other operations: router.post('/', (req, res) => { dbController.query( "SELECT * FROM users WHERE username = 'myUserName' ...

Avoid running postinstall scripts during package installation as a dependency

I have a package called x that includes a postinstall script. While developing, I utilized this script to perform necessary tasks for the package's development phase. Now that I have published the package, I do not want the postinstall task to be exe ...

I am interested in extracting information from the Firebase real-time database and showcasing it on my HTML webpage

I am struggling to display data from the Firebase real-time database on my HTML page. Even though I can see all the data perfectly in the console, it doesn't show up on the webpage. I attempted to use a for loop, but it still doesn't display the ...

Sluggish Beginnings: Firebase Firestore initializations delay in Cloud Functions

During a cold start (after deployment or after 3 hours), the function that requests a document from Firestore is noticeably slower compared to when it is used repeatedly. Cold Start: Function execution took 4593 ms, finished with status code: 200 Rapid ...

Retrieving dropdown options with the help of selenium and node.js

I'm looking to gather all the options from a dropdown menu and loop through them to submit a form. I need the list of values from the dropdown. The following Java code meets my requirements perfectly, but I am in need of the same functionality in Jav ...

Ways to effectively utilize the $getDownloadURL() promise within the ng-repeat directive in Angularjs 1.6

I am currently in the process of developing a Single Page Application (SPA) using AngularJS 1.6 along with Firebase for database and storage functionalities. One of my goals is to display an image from Firebase storage on my HTML page. I have implement ...

In Vue firebase, ensure that the prop is only passed down after it has been

I am facing an issue where I need to pass down the Firebase user as a prop from the root component to my child components. I managed to achieve this by passing the user to my router. However, the problem arises when I wrap my new Vue instance in an onAuthS ...

Dealing with the 'routes not found' error in a Node.js Express application (troubleshooting)

Attempting to address potential missing router errors in my app.js or router file has been a challenge for me. (various solutions found on Stack Overflow have not provided the correct resolution) The current state of my app.js or router files is functiona ...

Utilizing Node.js to Establish a Connection with Sybase

Is there a way to establish a connection to Sybase using node.js? I've come across npm-sybase, but I'm unsure of how to integrate it into my node.js application. ...

Top Method for Connecting Numerous Dependent HTTP Requests Without the Need for Multiple Subscriptions and Iterations

I'm working on an angular project where I have an API that creates a line item and then loops through to call the API for each modification before firing the print request. Currently, I am using multiple subscribes for this process and I was wondering ...

Make changes to the answer in an express/nodejs environment

I am currently working on creating multiple stream data in Node.js using express. Here is an example of how I create a URL: app.get('/temp/1', function(req, res){ res.send('hello, I am not modified') }) My question is: Can the resp ...

how to pass arguments to module.exports in a Node.js application

I have created a code snippet to implement a Node.js REST API. app.js var connection = require('./database_connector'); connection.initalized(); // I need to pass the connection variable to the model var person_model = require('./mod ...

A guide to integrating Social Login APIs (Google, Facebook, Apple) with NodeJs Express REST for a React Native application

Would it be possible to integrate Social Login APIs from Google, Facebook, and Apple with a React Native App using NodeJs Express REST? Can this implementation follow a similar process as it does for web applications? How would you go about creating the ...

Issues with ExtJs 7 (Community) npm build for Production installation failure

I have an ExtJs 7.0.0-CE application that functions properly when running locally on webpack-dev-server with npm run dev. However, when I build it for production and host it on IIS, it doesn't work. My build process involves using npm: npm run buil ...

What is the best way to incorporate parameters into a URL when working with Node.js and Jade?

When working with Jade, I have encountered a situation where I have two hyperlinks that both lead to the same page: a(href='/signup')#create-account Create Student Account a(href='/signup')#create-admin Create Teacher Account I need t ...

How are objects typically created in Node.js applications?

These code snippets are from Node.js tests, and I am curious about why one method of instantiating an object is favored over another? // 1 var events = require('events'); var emitter = new events.EventEmitter(); emitter.on('test', doSo ...

What could be causing the promises in Promise.all to remain in a pending state?

After restructuring my code to correctly utilize promises, I encountered a challenge with ensuring that the lastStep function can access both the HTML and URL of each page. To overcome this issue, I'm attempting to return an object in nextStep(). Alt ...

Contrasting the inclusion of the "route" keyword when defining routes in Express

Can you explain the distinction between router.route('/create') .post(validate(hotelValidation.createHotel), function (req, res) { and just router.post('/create', validate(hotelValidation.createHotel), function (req, res) { Are ...