16

我正在探索 firebase 云功能,并尝试使用 http 请求发送通知。

问题是即使我设法发送通知,请求总是超时。

这是我的脚本

/functions/index.js
const functions = require('firebase-functions');
const admin = require('firebase-admin');

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

exports.friendRequestNotification = functions.https.onRequest((req, res) => {

    const senderId = req.query.senderId;
    const recipientId = req.query.recipientId;
    const getRecipientPromise = admin.database().ref(`/players/${recipientId}`).once('value');
    const getSenderPromise = admin.database().ref(`/players/${senderId}`).once('value');

    return Promise.all([getRecipientPromise, getSenderPromise]).then(results => {

        const recipient = results[0];
        const sender = results[1];

        const recipientToken = recipient.child("notificationsInfo/fcmToken").val();
        const notificationAuthorization = recipient.child("notificationsInfo/wantsToReceiveNotifications").val();
        const recipientBadge = recipient.child("notificationsInfo/badgeNumber").val();
        const senderUsername = sender.child("username").val();

        const payload = {
            notification: {
              title: `FriendRequest`,
              body: `You have a new friend request from ${senderUsername}!`,
              badge: (recipientBadge+1).toString()
            }
        };

        if (notificationAuthorization) {

            return admin.messaging().sendToDevice(recipientToken, payload).then(response => {

            });

        }

        return admin.database().ref(`/players/${recipientId}/notificationsInfo/badgeNumber`).setValue(recipientBadge+1);

    });

});

另外,badgeNumber 似乎从未更新过,这与超时问题有关吗?

4

2 回答 2

25

HTTP 触发的 Cloud Functions 就像 Express 应用程序一样工作——您有一个响应对象 ( res),您需要在请求完成时使用它来发送一些东西。在这种情况下,您似乎可以执行以下操作:

return Promise.all([
  /* ... */
]).then(() => {
  res.status(200).send('ok');
}).catch(err => {
  console.log(err.stack);
  res.status(500).send('error');
});
于 2017-03-09T21:16:10.640 回答
3

@Michael Bleigh 对于这个问题的回答非常好,让我为未来的用户添加更多内容。

根据firebase文档:-

使用这些推荐的方法来管理函数的生命周期:

  • 通过返回JavaScript promise来解析执行异步处理的函数(也称为“后台函数”)。

  • 使用、或终止HTTP 函数。(这个问题的情况。)res.redirect()res.send()res.end()

  • 使用语句终止同步函数。return;

注意 管理函数的生命周期以确保其正确解析很重要。通过正确终止函数,您可以避免函数运行时间过长或无限循环产生过多费用。此外,您可以确保运行您的函数的 Cloud Functions 实例在您的函数成功达到其终止条件或状态之前不会关闭。

  • 您需要付费计划(Blaze,即用即付)来访问外部 API。

如果未配置计费帐户,您可能会在 firebase 函数日志中看到以下警告。

未配置结算帐号。外部网络无法访问,配额受到严格限制。配置结算帐户以删除这些限制

检查此链接以获取更多信息。

于 2019-08-09T07:30:34.997 回答