【问题标题】:Sending Notification With Firebase Cloud Functions to Specific users使用 Firebase Cloud 功能向特定用户发送通知
【发布时间】:2021-03-18 15:00:54
【问题描述】:

我在我的 firebase 群聊应用程序中使用 firebase 云功能,设置已经完成,但问题是当有人在任何组中发送消息时,所有用户都会收到该消息的通知,包括非组成员。

我只想向特定用户组发送通知,下面是我的 firebase 云功能代码 -

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const _ = require('lodash');

admin.initializeApp(functions.config().firebase);

exports.sendNewMessageNotification = functions.database.ref('/{pushId}').onWrite(event => {
const getValuePromise = admin.database()
                             .ref('messages')
                             .orderByKey()
                             .limitToLast(1)
                             .once('value');

return getValuePromise.then(snapshot => {
   const { text, author } = _.values(snapshot.val())[0];

    const payload = {
        notification: {
            title: text,
            body: author,
            icon: ''
        }
    };

    return admin.messaging()
                .sendToTopic('my-groupchat', payload);
 });
});

这真的很有帮助,如果有人能就此提出建议的话。

【问题讨论】:

  • 代码看起来正确,所以我认为问题在于您订阅该主题的成员的方式,您能分享您如何订阅该主题的成员吗?
  • 在我的代码中,我只传递 {pushId} 因此它会在对数据库执行任何写操作时生成通知,但我希望在组中执行写操作并且用户是该组的成员时发出通知.
  • my-groupchat要分享消息的用户或整个用户组的主题名称?如果是后者,您将必须创建一个单独的主题并订阅成员,这样才能接收它。
  • 整个用户组,但不是数据库中的所有用户,只有发起消息的组成员。那么如何通过云功能订阅每个组(动态创建的组)。
  • documentation 中有几个示例,您可以在服务器端或客户端进行。在您的情况下,您可以按照服务器端的示例进行操作,因为您需要批量添加它们。让我知道这是否有帮助。

标签: node.js firebase firebase-realtime-database google-cloud-functions firebase-cloud-messaging


【解决方案1】:

根据我们在 cmets 上的对话,我认为问题在于您使用的主题包含所有用户,即 my-groupchat 主题。解决方案是使用属于该子主题的用户创建一个新主题。

至于如何创建此类主题,documentation 中有几个示例,您可以在其中看到您可以在服务器端或客户端进行。在您的情况下,您可以按照服务器端的示例进行操作,因为您需要批量添加它们,但是随着新用户的添加,实现客户端方法可能会很有趣。

【讨论】:

    猜你喜欢
    • 2017-10-29
    • 2017-08-15
    • 2021-04-12
    • 2021-05-15
    • 2017-10-08
    • 1970-01-01
    • 2018-08-05
    • 2020-05-26
    • 1970-01-01
    相关资源
    最近更新 更多