通知未显示在数据库触发器上

时间:2017-07-08 12:16:48

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

我正在使用firebase云功能在调用数据库触发器时向用户发送通知。注册令牌保存在firebase数据库中。问题在于,尽管注册令牌已被保存,但这些设备中的通知并未显示。 这是 index.js

    const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);



exports.sendNotification = functions.database.ref('/Blog').onWrite(event => {
const title = event.data.child('title').val();

const token_no = event.data.child('token_no').val();


  const getDeviceTokensPromise = admin.database().ref(`/Token/${token_no}`).once('value');
  const getBody=admin.database().ref(`/Blog`).once('value');

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




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


    // Notification details.
    const payload = {
      notification: {
        title: 'You have a new Alert!',
        body: `${notify.child('title').val()}`,

      }
    };

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

数据库快照:

"Token" : {
"token_no" : {
  "ctxjePemYZE:APA91bFJXXyTkyvXOlSY...4VbWu7Vbf7itwbwZu9umSvg_tdB1lKD1d8g" : "true",
  "dgVszInjIW0:APA91bFZE3Av5unZTgp...RUeYb-CUhWjO1otqguhE9NTQZ8XgK6nRIW5" : "true"
}

}

1 个答案:

答案 0 :(得分:1)

更新2:

您的代码使用Object.keys(tokensSnapshot.val())来获取令牌。这意味着令牌必须是token_no下的键,而不是值。像这样:

"Token" : {
  "-KoWsMn9rCIitQeNvixr" : {
    "dK1FjGbNr6k:APA91b...S8JK2d69JpO" : "123" // token is the key, value is not significant; could be "123", true, or 0.
  },
  ...
}

<强>更新

您应该查看数据库触发器的documentation for the Event parameter,以便更好地了解paramsdata属性。 params提供对触发器引用中通配符的访问,data是快照。在您的代码中,您希望从快照中获取值。

添加以下更改:

const title = event.data.child('title').val();
const desp = event.data.child('desp').val();
const token_no = event.data.child('token_no').val()

const payload = {
  notification: {
    title: 'You have a new Alert!',
    body: `${Post.child('title').val()}`,  // <= CHANGED
    //icon: follower.photoURL
  }
};

运行您发布的代码,通过这些更改,我可以发送和接收通知。

有两个问题。第一个是这个声明:

const getDeviceTokensPromise = admin.database().ref(`/Token/{token_no}`).once('value');

token_no未定义。当您确定并想要替换其值时,您需要添加$

`/Token/${token_no}`

第二个问题是未定义Post,导致函数执行失败。检查您的功能日志:

const payload = {
  notification: {
    title: 'You have a new Alert!',
    body: `${Post.title}`,
    //icon: follower.photoURL
  }
};