firebase-当存储给某些用户的新数据在数据库中有特定数据时发送通知

yrefmtwq  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(303)

当实时数据库有新数据时,我想发送一个通知给在firebase firestore中有特定数据的某个用户。
与用户有关系的数据示例。
firebase实时发布数据
用户拥有他跟踪的组。
firebase firestore-用户数据
到目前为止,具体的数据是组名。
轻松地,向与海报组名具有相同组名的用户发送通知

a0x5cqrl

a0x5cqrl1#

您应该使用firebase云消息传递,而不是在cloudfirestore中搜索要通知的用户。这允许您为每个用户订阅与其所在组相对应的主题。
因为您需要为每个相关用户订阅相应的通知主题,所以这不是一个简单的“drop-in and-it-works”解决方案。关于如何做到这一点,请参阅目标平台的文档。

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);
      });
  });
});

相关问题