我正在尝试使用Firebase功能自动向iOS设备发送推送通知。更具体地说,现在当用户创建帖子时,它将包含一个ID,实际上是用户的FCM令牌,推送通知将从该ID发送给该用户。
为什么会这样,在创建帖子时,我的iOS设备不一定会收到单个推送通知,但很多?为什么对于给定的帖子,getResult函数可能被多次触发?
请参阅下面的代码。谢谢!
const functions = require('firebase-functions');
var admin = require('firebase-admin');
var firebase = require('firebase');
admin.initializeApp(functions.config().firebase);
var config = {
apiKey: "XXXXX",
authDomain: "YYYYY",
databaseURL: "ZZZZZ"
}
firebase.initializeApp(config);
firebase.database().ref('posts').on('child_added', function(snapshot1) {
snapshot1.forEach((child) => {
if (child.key == 'id') {
var token = child.val();
admin.database().ref('users').on('value', function(snapshot2) {
snapshot2.forEach(function(user) {
if (user.val().fcmToken == token) {
var newBadgeCount = user.val().badge + 1;
const payload = {
notification: {
title: 'Hello, World!',
body: 'Test Message!',
badge: '' + newBadgeCount,
sound: 'default'
}
};
function getResult(token) {
return result = admin.database().ref('fcmToken/' + token).once('value').then(allToken => {
if (allToken.val()) {
const token = Object.keys(allToken.val());
return admin.messaging().sendToDevice(token, payload).then(function (response) {
console.log("Successfully sent message: ", response.results[0].error);
}).catch(function (error) {
console.log("Error sending message: ", error);
});
};
});
}
function updateBadgeCount(badgeCount, userID) {
firebase.database().ref('users/' + userID + '/badge').set(badgeCount);
}
Promise.all([getResult(token)]).then(function(snapshots) {
updateBadgeCount(newBadgeCount, user.key);
});
};
});
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
};
});
});
答案 0 :(得分:1)
Firebase会触发一次'child_added'
选项的所有记录的每条记录,并在每个新子项添加后重新触发。因此,如果您想在新的写入选项上触发函数,则需要使用其他方法。
exports.sendNotifycation = functions.database.ref('/posts/{postId}')
.onWrite(event => {
Your new re-designed codes. (in case I will complete remain)
})