我正在使用 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)
部分,但不显示通知。我之前测试过云通知,它们有效,但由于某种原因不起作用。在日志中,它说:
成功发送消息:{ 结果:[ { 错误: [FirebaseMessagingError] } ]," "failureCount: 1," "successCount: 0,"
所以我知道直到
console.log('User: ' + followerID + ' is following: ' + followingID);
为止一切都有效。但我不确定通知功能是否被调用。我是否缺少分号或其他内容?我实在想不通。另外,failureCount
是什么意思?是说通知功能吗?
如 Cloud Functions doc 中所述,您需要使用 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;
});