用户通知用户通知不工作firebase(index.js文件)

时间:2018-02-12 03:55:02

标签: node.js firebase firebase-realtime-database firebase-cloud-messaging firebase-admin

我希望监控每个用户的通知树何时更改,并向他们发送通知。通知具有操作和用户名,这是通知所需的唯一内容

我在配置firebase工具后使用nodejs和npm我已将此文件部署到我的firebase控制台。不,我一生中从未使用过js

let functions = require('firebase-functions');

let admin = require('firebase-admin');

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

 exports.sendNotification = . 
functions.database.ref('/users/{uid}/notifications').onWrite((event) 
=> {

const uid = event.params.uid

if (!event.data.val()){
return console.log('User' , uid)
}

  const getDeviceTokensPromise = 



admin.database().ref(`/users/${uid}/notificationToken`).once('value');
  const getUserWithUid = admin.auth().getUser(uid);  

  return Promise.all([getDeviceTokensPromise, getUserWithUid]).then((results) => {
const tokensSnapshot = results[0];
const user = results[1];

// Check if there are any device tokens.
    if (!tokensSnapshot.hasChildren()) {
      return console.log('There are no notification tokens to send 
to.');
}
console.log('There are', tokensSnapshot.numChildren(), 'tokens to send notifications to.');
console.log('Fetched follower profile', follower);

    // Notification details.
    const payload = {
  notification: {
    title: `${user.username}`,
    body: `${user.action} `,

  },
};

// Listing all tokens.
const tokens = Object.keys(tokensSnapshot.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(tokensSnapshot.ref.child(tokens[index]).remove());
        }
      }
    });
    return Promise.all(tokensToRemove);
  });

});

这是我的数据库的屏幕截图:

database

这是我如何获得" notificationToken"存储在FB中的值:

(Messaging.messaging().fcmToken)!

我如何订阅通知:

        messaging.subscribe(toTopic: "users/\(uid)/notifications")

有人可以告诉我我做错了吗?

以下是日志的屏幕截图:

enter image description here

1 个答案:

答案 0 :(得分:1)

一个问题是令牌没有按照代码期望的方式存储在数据库中。令牌需要存储为notificationToken的子项,其中令牌为,而不是值。该值未使用,可以是任何内容,例如true。有关示例,请参阅Cloud Functions sample documentation

/users
    /Uid-12345
        displayName: "Bob Dole"
        /notificationTokens
            1234567890: true // <= NOTE: the key is the token
        photoURL: "https://lh3.googleusercontent.com/..."