Firebase云功能可通过推送通知将所有旧消息发送到群聊的新成员

时间:2020-04-29 13:03:14

标签: javascript android typescript firebase google-cloud-functions

我是android开发人员的初学者,所以如果我在代码中犯了一些基本错误,请原谅我。我正在构建一个用于托管活动的应用程序,并且该应用程序具有聊天功能。我已经开始进行基本的聊天,现在我想启用推送通知。

我没有打字稿(或javascript)的经验,所以这是一个真正的挑战。但是我使用了以下云功能:

const functions = require('firebase-functions');
//import admin module
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.database.ref('/messages/{post_id}/{message_id}').onCreate((snap: { val: () => any; }, context: any) => {

    const createdData = snap.val(); // data that was created
    const post_id = context.params.post_id; // ID of the post the message was sent in

    var ref = admin.database().ref('/participants/'+ post_id); //Get the Token from each participant of the chat
    ref.on("value", function(snapshot: any[]) {
      snapshot.forEach(function(childSnapshot) {
       var childData = childSnapshot.val();
       console.log(childData);
       const Token = childData.T; 

       console.log('The info is: ', createdData);
      console.log('The post Id is: ', post_id);
      console.log('The Token is: ', Token);

      const payload = {  // Push notification input
        notification: {
        title : createdData.n,
        body: createdData.message,
        tag: post_id
        }
    };

     admin.messaging().sendToDevice(Token, payload).then(function(response: { results: { error: any; }[]; }) { // sending the message
      console.log("Successfully sent message:", response);
      console.log(response.results[0].error);
  })
  .catch(function(error: any) {
      console.log("Error sending message:", error);
  })

      }); // end of the forEach loop
     });

    return
});

此代码有效,但存在一些问题。我的问题/问题如下:

1)当新用户进入群组聊天时,他/她从该用户加入之前已从群组中已发送的所有消息中接收推送通知。这可能是因为代码未正确终止。我尝试了一些操作,但是更改返回值时代码停止了。希望旧消息仍然可以被新用户阅读,但是我不希望当新用户加入时将它们全部推送。

2)我想知道这是否是可扩展功能。现在它可以正常工作,但是我在forEach循环中对单个消息进行了处理。有人知道这样的功能如何在1000个用户中起作用吗?对于正在发送的每条消息,我都会在我的云函数日志中收到以下警告:“函数返回了未定义的,预期的承诺或值”。目前看来这不是问题,但它暗示我的代码可能不是最佳的(也许与我在第1点中提到的问题有关?)。

谢谢!

0 个答案:

没有答案