Himanshu Shekher Jha
Himanshu Shekher Jha

Reputation: 1344

Get data from Firebase Real Time Database from a Cloud Function

I am using firebase function to send data type push notification on android devices. I am using this index.js Script. When user add a new message in firebase database then i am fetching userID from the firebase database.

Now i want to use this userID to fetch fcmToken of user.

Index.js

//import firebase functions modules
const functions = require('firebase-functions');
//import admin module
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);


// Listens for new messages added to messages/:userId
exports.pushNotificationData = functions.database.ref('/messages/{userId}').onWrite( event => {

    console.log('Push notification event triggered');

    //  Grab the current value of what was written to the Realtime Database.
    var valueObject = event.data.val();

    if(valueObject.photoUrl !== null) {
      valueObject.photoUrl= "Sent you a photo!";
    }

  // Create a notification
    const payload = {
        data: {
            title:valueObject.name,
            body: valueObject.text || valueObject.photoUrl,
            sound: "default"
        },
    };

  //Create an options object that contains the time to live for the notification and the priority
    const options = {
        priority: "high",
        timeToLive: 60 * 60 * 24
    };

 const user_id = event.params.userId;
return admin.messaging().sendToDevice(user_id, payload);


});

It is the structure of user profile in firebase database, from which i want to get fcmToken.

User Profile Info

Upvotes: 0

Views: 2396

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83093

The following should do the trick. You get the value of the token by querying the 'profiles/' + user_id reference with the once() method. Since once() is asynchronous and returns a promise, you have to wait the promise resolves in order to send the message.

exports.pushNotificationData = functions.database
  .ref('/messages/{userId}')
  .onWrite(event => {
    console.log('Push notification event triggered');

    //  Grab the current value of what was written to the Realtime Database.
    var valueObject = event.data.val();

    if (valueObject.photoUrl !== null) {
      valueObject.photoUrl = 'Sent you a photo!';
    }

    // Create a notification
    const payload = {
        data: {
            title:valueObject.name,
            body: valueObject.text || valueObject.photoUrl,
            sound: "default"
        }
    };

    //Create an options object that contains the time to live for the notification and the priority
    const options = {
      priority: 'high',
      timeToLive: 60 * 60 * 24
    };

    const user_id = event.params.userId;

    return admin
      .database()
      .ref('profiles/' + user_id)
      .once('value')
      .then(snapshot => {
        const token = snapshot.val().fcmToken;
        return admin.messaging().sendToDevice(token, payload, options);
      })
      .catch(error => {
        console.log('Error sending message:', error);
        return false;
      });
  });

In addition, note that you are using an old version of Cloud Functions (< v 1.0). You should update to the new version and new syntax. See https://firebase.google.com/docs/functions/beta-v1-diff

Upvotes: 2

Related Questions