当实时数据库有新数据时,我想向在Firebase Firestore中有特定数据的用户发送通知。
与用户有关系的数据示例。
Firebase实时数据后
并且用户拥有他所关注的群组。
Firebase Firestore-用户数据
截至目前,具体数据为组名。
轻松地,向与海报组名具有相同组名的用户发送通知
与其在Cloud Firestore中搜索用户以进行通知,不如使用Firebase Cloud Messaging。这允许您为每个用户订阅与他们所在的组相对应的主题。
因为你需要为每个相关用户订阅他们相应的通知主题,所以这不是一个简单的";顺便拜访一下就行了";解决方案有关如何做到这一点,请参阅目标平台的文档。
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
export const notifyGroupsOfNewPost = functions.database.ref("/Poster/{postId}").onCreate(async (snapshot, context) => {
/* avoid using `snapshot.val()` unless you need all of the data at once */
const postGroups = snapshot.child("Groups").val(); // assumed to be parsed as an array, make sure to handle non-array values gracefully
if (postGroups === null) {
throw new Error('Groups of new post missing');
}
return Promise.all(postGroups.map((group) => {
const message = {
/* note: only send data used for creating the notification message,
the rest of it can be downloaded using the SDK once it's needed */
data: {
Impact: snapshot.child("Impact").val(),
Subject: snapshot.child("Subject").val(),
TT: snapshot.child("TT").val()
},
topic: group /* you could also use `${group}-newpost` here */
};
return admin.messaging().send(message)
.then((messageId) => {
console.log(`Successfully notified the ${group} group about new post #${snapshot.key} (FCM #{$messageId})`);
})
.catch((error) => {
console.error(`Failed to notify the ${group} group about new post #${snapshot.key}:`, error);
});
});
});