当有人使用 Firebase 关注其他人时,您如何触发云功能?我正在使用 Atom 和 Xcode



我正在使用Firebase,我想在"人员a"跟在"人员B"后面时触发通知。

这是我的代码:

exports.observeFollowing = functions.database.ref('/added/{followerID}/{followingID}').onCreate((snapshot, context) => {
var followerID = context.params.followerID;
var followingID = context.params.followingID;
console.log('User: ' + followerID + ' is following: ' + followingID);
//trying to figure out fcmtoken to send a notification
return admin.database().ref('/users/' + followingID).once('value', snapshot => {
var userWeAreFollowing = snapshot.val();
return admin.database().ref('/users/' + followerID).once('value', snapshot => {
var userDoingTheFollowing = snapshot.val();
var payload = {
notification: {
title: "Someone added you as a friend",
body: userDoingTheFollowing.username + ' is now following you'
}
}
return admin.messaging().sendToDevice(userWeAreFollowing.fcmToken, payload)
.then(response => {
console.log("Successfully sent message:", response);
return response
}).catch(function(error) {
console.log("Error sending message:", error);
});
})
})
});

控制台打印('User: ' + followerID + ' is following: ' + followingID)部分,但不显示通知。我以前测试过云通知,它们有效,但由于某种原因,这不起作用。在日志中,它写道:

成功发送消息:{results:[{error:[FirebaseMessagingError]}],"failureCount:1"successCount:0,";

所以我知道console.log('User: ' + followerID + ' is following: ' + followingID);之前的一切都有效。但我不确定是否调用了通知函数。我是缺少分号还是其他什么?我真的想不通。另外,failureCount是什么意思?它是在谈论通知功能吗?

如Cloud Functions文档中所述,您需要使用promise来管理异步Firebase操作。您使用的是once()方法的回调版本:您需要使用promise版本,如下所示:

exports.observeFollowing = functions.database.ref('/added/{followerID}/{followingID}').onCreate((snapshot, context) => {
const followerID = context.params.followerID;
const followingID = context.params.followingID;
let userWeAreFollowing;
console.log('User: ' + followerID + ' is following: ' + followingID);

return admin.database().ref('/users/' + followingID).once('value')
.then(snapshot => {
userWeAreFollowing = snapshot.val();
return admin.database().ref('/users/' + followerID).once('value')
})
.then(snapshot => {
const userDoingTheFollowing = snapshot.val();
const payload = {
notification: {
title: "Someone added you as a friend",
body: userDoingTheFollowing.username + ' is now following you'
}
}
return admin.messaging().sendToDevice(userWeAreFollowing.fcmToken, payload)
}).catch(function (error) {
console.log("Error sending message:", error);
return null;
});
});

如果您想在成功后在控制台中记录消息,请执行以下操作:

// ...
.then(snapshot => {
const userDoingTheFollowing = snapshot.val();
const payload = {
notification: {
title: "Someone added you as a friend",
body: userDoingTheFollowing.username + ' is now following you'
}
}
return admin.messaging().sendToDevice(userWeAreFollowing.fcmToken, payload)
})
.then(response => {
console.log("Successfully sent message:", response);
return null;
}).catch(function (error) {
console.log("Error sending message:", error);
return null;
});

最新更新