Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read Firebase Database entry in Firebase Cloud Functions' index.js?

I am trying to create device to device push notifications for an iOS app using Firebase Cloud functions. I want to trigger an event whenever a new child is created in database at reference '/user-notifications/{notificationRecipientUid}/{challengeId}'. Here is my index.js code:

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

exports.sendWinLoseOrTieNotification = functions.database.ref('/user-notifications/{notificationRecipientUid}/{challengeId}').onWrite(event => {
...
const challengeId = event.params.challengeId;

functions.database.ref('/challenges/' + challengeId).once('value').then(function(snapshot) {
    const challengerUid = snapshot.val().challengerUid;
    ...
});
});

When a new child is added in the database at that location, I get this error, "TypeError: functions.database.ref(...).once is not a function", in Firebase Console's Functions Logs. So there is no 'once' method available on ref like in web api:

firebase.database().ref('...').once('value').then(function(snapshot) { ... });

My question is: How to read an existing database value inside index.js?

like image 684
naeemjawaid Avatar asked May 01 '17 10:05

naeemjawaid


People also ask

How do I read Firebase logs?

You can see logs in real time using the Firebase console. Choose your project, click the Functions product on the left, then click the Logs tab.

How do you read data from Firebase Realtime Database Web?

For reading a data from the Firebase Realtime database, Firebase has two methods on() and once() . on() method to retrieve data. This method is taking the event type as “value” and then retrieves the snapshot of the data. When we add val() method to the snapshot, we will get the JavaScript representation of the data.


1 Answers

Well, the solution is to use admin instead of firebase like so:

admin.database().ref('...').once('value').then(function(snapshot) {
    ...
});
like image 122
naeemjawaid Avatar answered Oct 19 '22 11:10

naeemjawaid