通过云功能从Firebase实时数据库获取数据

时间:2018-09-09 12:14:03

标签: firebase firebase-realtime-database google-cloud-functions

我正在使用firebase函数在android设备上发送数据类型推送通知。我正在使用这个index.js脚本。当用户在Firebase数据库中添加新消息时,我正在从Firebase数据库中获取用户ID。

现在,我想使用此userID来获取用户的fcmToken。

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);


});

这是Firebase数据库中用户配置文件的结构,我想从中获取fcmToken。

User Profile Info

1 个答案:

答案 0 :(得分:1)

以下应该可以解决问题。您可以通过使用'profiles/' + user_id方法查询once()引用来获得令牌的值。由于once()是异步的并返回承诺,因此您必须等待承诺解析才能发送消息。

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;
      });
  });

此外,请注意,您正在使用旧版本的Cloud Functions(新语法。参见https://firebase.google.com/docs/functions/beta-v1-diff