Javascript Firebase云函数始终超时
我正在探索firebase云函数,并尝试通过http请求发送通知 问题是,即使我设法发送通知,请求也总是超时 这是我的剧本 /函数/index.jsJavascript Firebase云函数始终超时,javascript,node.js,firebase,firebase-cloud-messaging,google-cloud-functions,Javascript,Node.js,Firebase,Firebase Cloud Messaging,Google Cloud Functions,我正在探索firebase云函数,并尝试通过http请求发送通知 问题是,即使我设法发送通知,请求也总是超时 这是我的剧本 /函数/index.js const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); exports.friendRequestNotification
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);
});
});
另外,似乎“从未更新”中的徽章号与超时问题有关吗?HTTP触发的云函数的工作原理与Express apps一样--您有一个响应对象(
res
),在请求完成时需要使用它来发送内容。在这种情况下,您可以执行以下操作:
return Promise.all([
/* ... */
]).then(() => {
res.status(200).send('ok');
}).catch(err => {
console.log(err.stack);
res.status(500).send('error');
});
@Michael Bleigh的答案对于这个问题非常好,让我为未来的用户补充更多 根据firebase文档:- 使用这些推荐的方法来管理您的产品的生命周期 职能:
- 解析执行异步处理的函数(也称为 “后台函数”),返回一个
- 使用
、res.redirect()
或res.send()
终止HTTP函数。(本问题中的情况)res.end()
- 用
返回终止同步函数代码>语句
- 您需要一个付费计划(Blaze,按量付费)来访问外部API。
查看更多信息。对于其他可能遇到此线程的人,请记住,向第三方发送HTTPS请求时,要求您已支付Firebase帐户;为了防止滥用,你不能用免费帐户在谷歌之外发送HTTP请求。哦,我明白了,你从哪里找到这些信息的?那么数据库触发器呢?在Firebase定价页面上,脚注3说“Spark计划只允许对谷歌所有服务的出站网络请求。在Blaze计划中,云功能提供永久免费层。”请参阅Firebase文档中的更多详细信息: