云函数为dataSnapshot返回null

时间:2017-12-30 08:27:58

标签: javascript firebase firebase-cloud-messaging google-cloud-functions

我正在使用云通知在实时数据库中更新某些数据时发送通知,而我发送的通知也包含一些来自数据库的详细信息     const functions = require('firebase-functions');     const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.notifyUsers = functions.database.ref('/').onUpdate(event => {
  var message = event.data.val();
  admin.database().ref('users/'+message.uid).on('value', function(dataSnapshot) {
    var usernameOfSender = dataSnapshot.child('username').val();
    console.log('message: '+message.val());
    console.log('dataSnapshot.val: '+dataSnapshot.val());
    console.log('usernameOfSender: '+usernameOfSender);
    // Notification details.
    const text = message.message;
    const payload = {
      notification: {
        title: `${usernameOfSender} posted ${text ? 'a message' : 'an image'}`,
        body: text ? (text.length <= 100 ? text : text.substring(0, 97) + '...') : '',
        icon: dataSnapshot.child('profilePic').val() || '/images/defaultProfilePic.png',
        click_action: `https://${functions.config().firebase.authDomain}`
      }
    };
    // Get the list of device tokens.
    return admin.database().ref('fcmTokens').once('value').then(allTokens => {
      if (allTokens.val()) {
        // Listing all tokens.
        const tokens = Object.keys(allTokens.val());

        // Send notifications to all tokens.
        return admin.messaging().sendToDevice(tokens, payload).then(response => {
          // For each message check if there was an error.
          const tokensToRemove = [];
          response.results.forEach((result, index) => {
            const error = result.error;
            if (error) {
              console.error('Failure sending notification to', tokens[index], error);
              // Cleanup the tokens who are not registered anymore.
              if (error.code === 'messaging/invalid-registration-token' ||
                  error.code === 'messaging/registration-token-not-registered') {
                tokensToRemove.push(allTokens.ref.child(tokens[index]).remove());
              }
            }
          });
          return Promise.all(tokensToRemove);
        });
      }
    });
  });
});

当我检查我的firebase控制台时,这就是我得到的:

usernameOfSender: null
dataSnapshot.val: null
message: [object Object]

并且通知为null,使用默认的个人资料图片发布图像。

0 个答案:

没有答案