javascript - Firebase 云功能总是超时

标签 javascript node.js firebase firebase-cloud-messaging google-cloud-functions

我正在探索 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 好像一直没更新,是不是跟超时问题有关?

最佳答案

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');
});

关于javascript - Firebase 云功能总是超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42705398/

相关文章:

javascript - 如何将 react 路线绑定(bind)到显示的对话框?

arrays - 从 mongoDB 集合中删除数组项

java - 如何从 firebase 检索多个数据并将其显示在 TextView 中?

android - 开始使用新的 Firebase 网站,我在测试 Android 身份验证示例程序时遇到此错误

javascript - ASP :LinkButton created via literal control will not fire code behind

javascript - 为什么我的输出重复?

node.js - 将 PhantomJS 与/Node 一起使用并设置自定义用户代理

javascript - 当状态对象发生变化时更新上下文

javascript - Firebase Cloud 函数未被调用

javascript - 计算Javascript中字符串中字符的出现次数