我正在尝试创建一个Firebase Cloud Function,该功能将在我的本机应用程序的feed上侦听新帖子,然后将所有帖子的通知发送给所有用户。我决定从小的角度开始,并且首先了解Firebase Cloud功能。
在针对实时数据库触发器的firebase文档之后,我尝试创建下面代码中所示的函数。我相信该功能可以很好地部署到我的数据库,因为这是在命令提示符下输出的:
此外,我的firebase项目似乎也接收并存储了该函数:
但是,当我返回数据库并在指定路径上创建新节点时,什么也没有发生。此外,我在“功能”标签中检查了“日志”,没有任何内容。
任何帮助将不胜感激...谢谢!
编辑2 尝试包括admin SDK(如下所示),但没有更改。
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendPushNotifications = functions.database.ref('/{organization}/posts/')
.onCreate((snapshot, context) => {
const post = snapshot.val();
console.log('Uppercasing', context.params.organization, post);
const uppercasePost = post.toUpperCase();
// You must return a Promise when performing asynchronous tasks inside a Functions such as
// writing to the Firebase Realtime Database.
// Setting an "uppercase" sibling in the Realtime Database returns a Promise.
return snapshot.ref.parent.child('cloudFunctionTest').set(uppercasePost);
});
答案 0 :(得分:2)
您可能没有在正确的路径下创建“帖子”。
事实上,使用您的代码
exports.sendPushNotifications = functions.database.ref('/{organization}/posts/')
.onCreate((snapshot, context) => {})
将为任何节点触发云功能,例如以下节点
ksigapp // <- Root of your database
- abcd //<- This corresponds to {organization} in your code
- posts: "lowercase"
- efgh // <- This corresponds to {organization} in your code
- posts: "whatever"
- IUUY7676676fgfgfg7 //<- This corresponds to {organization} in your code
- posts: "lowercase2"
....
其次,posts
的值必须是字符串,并且不能是对象,因为post.toUpperCase();
会生成错误(您不能将此方法应用于对象)。
换句话说,以下内容将产生错误:
ksigapp // <- Root of your database
- abcd
- posts
- postId
- author: "John"
- subject: "Lorem ipsus"
因此您很可能必须重新考虑您的Cloud Function路径
您可以研究以下Firebase官方示例:https://github.com/firebase/functions-samples/tree/master#rtdb