从 firebase 发送私人消息

Send private message from firebase

我是 Firebase 的新手。我的问题是,在 firebase realtimedb 中,我想从 firebase 推送私人消息。在 socket io 中,这可以通过这种方式完成。 //给个人socketid(私信) io.to(socketId).emit(/ ... /); 我如何在 firebase 中执行此操作,另一件事是 firebase 实时数据库具有动态更新或添加其规则的任何权限

您可以创建一个名为 notifications 的新节点,其子节点以用户 ID 作为键:

{
  notifications: {
    user_id_1: { },
    user_id_2: { },
    user_id_3: { }
  }
}

如果您需要向 user_id_1 发送通知,只需将包含消息的新节点添加到 notifications/user_id_1。确保用户正在像这样收听该节点:

import { getDatabase, ref, onValue} from "firebase/database";

const db = getDatabase();
const msgRef = ref(db, 'notifications/' + curUserId);

onValue(msgRef, (snapshot) => {
  const data = snapshot.val();
  // show the message
});

要确保用户可以阅读他们自己的消息,您可以使用安全规则:

{
  "rules": {
    "notifications": {
      "$uid": {
        ".read": "auth.uid == $uid"
      }
    }
  }
}