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);
});
});
});
1条答案
按热度按时间a0x5cqrl1#
您应该使用firebase云消息传递,而不是在cloudfirestore中搜索要通知的用户。这允许您为每个用户订阅与其所在组相对应的主题。
因为您需要为每个相关用户订阅相应的通知主题,所以这不是一个简单的“drop-in and-it-works”解决方案。关于如何做到这一点,请参阅目标平台的文档。