user13083550
user13083550

Reputation: 1

How to query value from specific Realtime Database path?

I've written a Firebase Cloud Function that pushes a notification to a topic whenever a certain value (timeTag) is changed:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.database.ref('/books/{category}/pages/{page}/timeTag').onUpdate((change, context) => {

    const category = context.params.category;
    const page = context.params.page;

    const categoryName = admin.database().ref('/books/'+`${category}`+'/name/');
    const pageName = admin.database().ref('/books/'+`${category}`+'/pages/'+`${page}`+'/name/');

    const data = change.data;
    console.log(`${categoryName}`)
    console.log(`${pageName}`)

    console.log('Message received');

    const payLoad = {
        notification:{
            title: 'There's an update in '+`${categoryName}`,
            body:  'The page that's been updated is '+`${pageName}`,
            sound: "default"
        }
    };
    return admin.messaging().sendToTopic("all", payLoad);
});

The database is structured like this:

books:
      {categoryID}
      name: categoryName
      pages:
            {pageID}
            name: pageName

Currently the names are the complete URL's in the database; for example, https://my-project.firebaseio.com/books/-LxzDYhk-t3LGRGifEyz/name. In this case, name is the key for the value I want. This is problematic because the FCM notification ends up being There's an update in https://my-project.firebaseio.com/books/-LxzDYhk-t3LGRGifEyz/name instead of There's an update in categoryOne.

What I'm trying to do is set the variables as the values for the name keys, instead of the URLs themselves. What have I missed?

Thanks in advance!

Upvotes: 0

Views: 130

Answers (1)

Michael Bleigh
Michael Bleigh

Reputation: 26343

You are creating references to the data, but not actually fetching it. You need something like this:

exports.sendNotification = functions.database.ref('/books/{category}/pages/{page}/timeTag').onUpdate(async (change, context) => {

    // ...

    const categoryNameSnap = await admin.database().ref('/books/'+`${category}`+'/name/').once('value');
    const categoryName = categoryNameSnap.val();
    const pageNameSnap = await admin.database().ref('/books/'+`${category}`+'/pages/'+`${page}`+'/name/').once('value');
    const pageName = pageNameSnap.val();

    // ...
});

Note that the function has been made async (to allow for a wait on the promise returned by .once('value') and the values are being pulled from the resulting snapshot.

These docs have some more info generally about retrieving data from the Realtime Database.

Upvotes: 1

Related Questions