Why is ForEach in cloud function leads to error credentialkey is not defined

Viewed 21

I start writing a cloud function to determine and remove credential entries from my firebase database.
The structure is as following:
enter image description here

Under the "user" reference you find a lot of child entries that also contains 1 or more childs with the credential information (e.g. Demo with accesslevel and validuntil).
The cloufunction should get the snapshot of the user reference and should iterate over all childs and then iterate over there childs (which are the credentials) to get the validuntil information.
After comparing the time (validuntil is the time in milliseconds) it should then remove all credential entries that are not longer valid.
Here you find the cloud function code that should print out the key and the validuntil information .

    exports.cleanupExpiredCredentials = functions.pubsub.topic('cleanup_credentials').onPublish((event) => {
    console.log('Start cleanup expired credentials.');
        
    return dbrefroot.child('/credentials/users')
    .get()
    .then(snapshot => {
        
        const promises = [];
        snapshot.forEach( userSnapshot => {
            var userSnapshotKey = userSnapshot.key;
            console.log(`user key: ${userSnapshotKey}`);

            userSnapshot.forEach( credentialSnapshot => {
                var credentialkey = credentialSnapshot.key;
                var valid_until = credentialSnapshot.child('validuntil').val();
                console.log(`credential key: ${credentialkey}  -  valid_until: ${valid_until}`);
            });
            promises.push(credentialkey);
        });

        return Promise.all(promises);
    })
    .then((results) => {
        console.log('End cleanup expired credentials.');
        return
    })
    .catch(error => {
        console.log('The following error accoured:', error);
    });    
});

When I start the cloud function I got the following output in the logs:
Function execution started
Start cleanup expired credentials.
user key: 0h8CNgePTZfjojm1HQ9nGDNtmKs1
credential key: Demo - valid_until: 0
The following error accoured: ReferenceError: credentialkey is not defined at snapshot.forEach.userSnapshot (/workspace/index.js:424:27)

So the first Iteration seems to fine but then the error accoured. Can someone could help me with the code? It's not finished yet because the comparsion is missing and also the removement of the credentials that are not longer valid.

Kindly regards Frank

0 Answers
Related