【问题标题】:cloud functions notifications for android适用于 Android 的云功能通知
【发布时间】:2019-03-03 03:41:48
【问题描述】:

我正在尝试使用适用于 Android 应用程序的 Firebase 云功能向多个用户发送通知

这就是我所做的。

exports.sendNotification = functions.database.ref('/notifications/messages/{pushId}')
  .onWrite(event => {
    const message = event.data.current.val();
    const senderUid = message.userId;
    const groupId = message.groupId;
    const promises = [];


    const getInstanceGroupUsers = admin.database().ref(`/groups/${groupId}/users`).once('value').then((snapshot) => {
      if (snapshot.exists()) {
        snapshot.forEach((child) => {
          var receiverUid = child.key;

          console.log(receiverUid);

          if (senderUid == receiverUid) {
            //if sender is receiver, don't send notification
            promises.push(event.data.current.ref.remove());
            return Promise.all(promises);
          }

          const getInstanceIdPromise = admin.database().ref(`/users/${receiverUid}/message_token`).once('value');
          const getReceiverUidPromise = admin.auth().getUser(receiverUid);
          return Promise.all([getInstanceIdPromise, getReceiverUidPromise]).then(results => {
            const instanceId = results[0].val();
            const receiver = results[1];
            console.log('notifying ' + receiverUid + ' about ' + message.body + ' from ' + senderUid);

            const payload = {
              notification: {
                title: receiver.displayName,
                body: message.message,
                icon: receiver.photoURL
              }
            };

            admin.messaging().sendToDevice(instanceId, payload)
              .then(function(response) {
                console.log("Successfully sent message:", response);
              })
              .catch(function(error) {
                console.log("Error sending message:", error);
              });
          });

        });
      }
    });

  });

我以前从未在 JS 中编写过代码,也从未使用过云功能,但我在这里尝试做的是从节点 /notifications/messages/{pushId} 获取消息的 groupeId,然后对组的所有用户进行循环以发送通知。

我不知道我是否做得对,但这些是我得到的错误:

22:14 错误每个 then() 应该返回一个值或抛出 承诺/总是返回

28:34 错误应为 '===' 而看到的是 '==' eqeqeq

36:30 警告避免嵌套承诺
承诺/不嵌套

36:94 错误 每个 then() 都应该返回一个值或抛出 承诺/总是返回

49:27 警告避免嵌套承诺
承诺/不嵌套

49:27 警告避免嵌套承诺
承诺/不嵌套

50:37 警告意外的函数表达式
首选箭头回调

50:37 错误 每个 then() 都应该返回一个值或抛出 承诺/总是返回

53:38 警告意外的函数表达式
首选箭头回调

欢迎任何形式的帮助!

【问题讨论】:

  • 错误实际上告诉您问题所在。哪些你不明白?

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


【解决方案1】:

这是摆脱错误和大多数警告的方法

exports.sendNotification = functions.database.ref('/notifications/messages/{pushId}').onWrite(event => {
    const message = event.data.current.val();
    const senderUid = message.userId;
    const groupId = message.groupId;
    const promises = [];


    const getInstanceGroupUsers = admin.database().ref(`/groups/${groupId}/users`).once('value')
    .then((snapshot) => {
        if (snapshot.exists()) {
            snapshot.forEach((child) => {
                var receiverUid = child.key;

                console.log(receiverUid);
                //*** use === instead of ==
                if (senderUid === receiverUid) {
                    //if sender is receiver, don't send notification
                    promises.push(event.data.current.ref.remove());
                    return Promise.all(promises);
                }

                const getInstanceIdPromise = admin.database().ref(`/users/${receiverUid}/message_token`).once('value');
                const getReceiverUidPromise = admin.auth().getUser(receiverUid);
                return Promise.all([getInstanceIdPromise, getReceiverUidPromise])
                .then(results => {
                    const instanceId = results[0].val();
                    const receiver = results[1];
                    console.log('notifying ' + receiverUid + ' about ' + message.body + ' from ' + senderUid);

                    const payload = {
                        notification: {
                            title: receiver.displayName,
                            body: message.message,
                            icon: receiver.photoURL
                        }
                    };
                    //*** added return, so this .then returns a something as required
                    return admin.messaging().sendToDevice(instanceId, payload);
                }) //*** avoid nesting promises, 
                //*** use arrow functions as "prefered" and a return value (the return is implied)
                .then((response) => console.log("Successfully sent message:", response))
                .catch((error) => console.log("Error sending message:", error));
            });
        } 
        //*** now this .then returns something
        return undefined;
    });
});

查看标记为//***的cmets

剩下的唯一警告是嵌套的 Promise 警告之一 - 因为关于代码中的逻辑是深不可测的

if (senderUid === receiverUid) {

你为什么要返回 Promise.all 那里?

另一个 Promise.all 也很难移动,因为我不明白你的代码在 snapshot.forEach 中试图实现什么

但是错误现在应该处理

【讨论】:

  • 我看到了一个在 2 个用户之间发送消息的简单应用程序中发送通知的示例,我尝试将其调整为我的 firebase 数据库,这更复杂,事情是我刚刚开始开发今年的java android,我以前从未见过javascript。我试图向一组特定用户发送通知。但我想我做错了。但我想了解你在那里做了什么,看看它是否有效,非常感谢注意:对不起我的英语!!!
猜你喜欢
  • 2017-09-28
  • 1970-01-01
  • 2017-09-16
  • 2017-11-24
  • 2017-12-07
  • 1970-01-01
  • 2019-02-23
  • 1970-01-01
  • 2019-12-18
相关资源
最近更新 更多