By naeemjawaid


2017-05-01 10:09:29 8 Comments

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?

1 comments

@naeemjawaid 2017-05-01 10:48:37

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

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

@Frank van Puffelen 2017-05-01 14:32:57

The reason for this is that you import the admin SDK into a const called admin: const admin = require('firebase-admin')

@Waza_Be 2017-10-05 14:08:50

I get an error 500 while using this code, and I don't get how to debug.. Webhook call failed. Error: 500 Internal Server Error

@naeemjawaid 2017-10-06 13:11:01

@Waza_Be I'm not a web dev, but I think webhook is for loading external packages like firebase-functions, node mailer etc. You have to install it in your computer for requiring such packages, as in: const functions = require('firebase-functions'); In this case, you are not deploying to your machine but a google server, which has all the webhooks installed, so you will not get this error there.

@naeemjawaid 2017-10-06 13:14:39

@Waza_Be Do this, if you haven't already: npm install [email protected] --save npm install -g firebase-tools Go to project directory and run: firebase login firebase init functions Put code in functions/index.js, then run: firebase deploy --only functions I think that will do. Check firebase.google.com/docs/functions/get-started for detailed guide.

Related Questions

Sponsored Content

3 Answered Questions

2 Answered Questions

1 Answered Questions

0 Answered Questions

0 Answered Questions

1 Answered Questions

0 Answered Questions

Sponsored Content