Search code examples
node.jsfirebase-realtime-databasefirebase-admin

Use query data from Firebase Realtime DB as input for another function


So I'm using Firebase Realtime Database to store some data and would like to use the results of a query, as an input for another function (generate signed URLs). My code is as follows:

// initialize the empty list
let lista = []

// define the async function that does everything
async function queryandgeturls() {
    // make the query to the firebase realtimeDB
    await ref.orderByChild('timestamp_start').startAt(timestamp1).endAt(timestamp2).on('child_added', (snapshot) => {
        lista.push(snapshot.val().name);
    });

    // use the list as input for another function to get Signed URLs
    for (const fileName of lista) {
        const [signedUrl] = await storage.bucket(bucketName).file(fileName).getSignedUrl({
            version: 'v4',
            expires: Date.now() + 15 * 60 * 1000,
            action: 'read'
        });
        console.log(`The signed URL for ${fileName} is ${signedUrl}`);
    }
};

// call the function
queryandgeturls().catch(console.error);

No luck so far. Any leads?


Solution

  • The on method keeps an open listener to the event that can be called repeatedly, so it doesn't return a promise (since a promise can only resolve once). So the await ref.orderByChild....on('child_added'... in your code doesn't do anything, which probably explains the problem.

    To properly solve this problem, use once('value', ... and don't combine await and callbacks.

    async function queryandgeturls() {
        // make the query to the firebase realtimeDB
        const results = await ref.orderByChild('timestamp_start').startAt(timestamp1).endAt(timestamp2).once('value');
        results.forEach((snapshot) => {
            lista.push(snapshot.val().name);
        });
        ...