javascript - Firestore 的 Firebase Cloud Functions 未触发
问题描述
无法在我的集合的 onWrite 上触发 Firestore 的 Firebase 云功能。尝试为聊天应用设置设备到设备的推送通知。功能已部署并按按需付费计划进行,但不会触发文档更改、更新或“聊天”集合中的创建。Firebase 云消息传递应该发送推送并写入日志。两者都没有发生。Push 正在与其他来源合作。
感谢您的帮助,希望设备到设备的推送通知更容易,计划是观看聊天文档并在更新或创建新对话时触发推送通知。接受其他想法。谢谢
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotification = functions.firestore
.document('chats/{chatID}')
.onWrite((data, context) => {
// Get an object representing the document
console.log('chat triggered');
// perform desired operations ...
// See documentation on defining a message payload.
var message = {
notification: {
title: 'Hello World!',
body: 'Hello World!'
},
topic: context.params.chatID
};
// Send a message to devices subscribed to the provided topic.
return admin.messaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
return true
})
.catch((error) => {
console.log('Error sending message:', error);
});
});
更新:我正在使用“firebase-functions”:“^1.0.1”
更新:更新了代码以反映我们当前已部署的内容,但仍然无法正常工作。
解决方案
您可能会在新库 (v1.0) 中使用旧语法(V1.0 之前)。请参阅迁移指南:https ://firebase.google.com/docs/functions/beta-v1-diff并检查 package.json 文件中的版本。
此外,请注意,云函数必须始终返回一个 Promise(或者如果你不能,至少一个值,对于异步函数)。请参阅此文档(和相关视频),其中详细说明了这一点:https ://firebase.google.com/docs/functions/terminate-functions
你应该这样修改你的代码:
如果您使用的是 Cloud Functions 1.0 或更高版本:
exports.sendNotification = functions.firestore
.document('chats/{chatID}')
.onWrite((change, context) => {
返回:
exports.sendNotification = functions.firestore
.document('chats/{chatID}')
.onWrite((change, context) => {
// Get an object representing the document
console.log('chat triggered');
// perform desired operations ...
// See documentation on defining a message payload.
var message = {
notification: {
title: 'Hello World!',
body: 'Hello World!'
},
topic: context.params.chatID. //<- If you are using a CF version under v1.0 don't change here
};
// Send a message to devices subscribed to the provided topic.
return admin.messaging().send(message). //<- return the resulting Promise
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
return true; //<- return a value
})
.catch((error) => {
console.log('Error sending message:', error);
//return. <- No need to return here
});
});
推荐阅读
- javascript - JQuery - 在列表更改显示/隐藏具有 ID 匹配选项值的元素
- xamarin - Xamarin Android 构建只是在启用链接器时挂起
- swift - 如何修复 Swift 5.1 中的“使用未声明的类型”错误?
- flutter - I/Process (22926):发送信号。PID:22926 SIG:9 失去与设备的连接。在颤振中使用firebase时
- python - 如何将函数别名为 SymPy 中的符号
- r - 将一行拆分为具有 R 中条件的列
- python - 强制 numpy 函数的输出形状
- java - 如何更改 LiveData 列表的顺序?
- javascript - Hooks 规则顶层在哪里
- apache-spark - 如何理解 Spark 中的这段代码