0

I'm trying to schedule a daily execution of a firebase function, but I can't access the data from the database.

I can access it using functions.database, but not in functions.pubsub.schedule.

const functions = require('firebase-functions');
var admin = require("firebase-admin");
admin.initializeApp({
    credential: admin.credential.applicationDefault(),
    databaseURL: 'https://<myApp>.firebaseio.com'
});

exports.todoDia = functions.pubsub.schedule('59 22 * * *').timeZone('America/Sao_Paulo').onRun((context) => {
    admin.database().ref('users').once('value', (snapshot) => {
        snapshot.forEach(child => {
            console.log('=================>>> ' + child.key);
        });
    });
    return null;
});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Itapox
  • 579
  • 1
  • 7
  • 25

1 Answers1

1

Your code is failing to handle the fact that data is loaded from Firebase asynchronously.

Right now your return null runs immediately, well before the data is loaded, which signals to the Cloud Functions container that your code is done, and that it can shut down the container. Since this happens before the data is loaded the callback never fires; or in some cases it may fire, or partially fire, all of which are even worse.

The solution is always the same: you need to return a promise that resolves when all work is done. In your case, that can be as simple as:

exports.todoDia = functions.pubsub.schedule('59 22 * * *').timeZone('America/Sao_Paulo').onRun((context) => {
 //  Use return here                                  Use then here
    return admin.database().ref('users').once('value').then((snapshot) => {
        snapshot.forEach(child => {
            console.log('=================>>> ' + child.key);
        });
        return null; //  Use return inside the callback        
    });
});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807