我是Firebase云功能的新手,我的情况是每当数据库中发布新文章时,我都需要向应用程序用户显示通知。
我的代码
var functions = require('firebase-functions');
var admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/article/{articleId}')
.onWrite((event: { data: any; }) => {
var eventSnapshot = event.data;
var str1 = "Author is ";
var str = str1.concat(eventSnapshot.child("author").val());
console.log(str);
var topic = "android";
var payload = {
data: {
title: eventSnapshot.child("title").val(),
author: eventSnapshot.child("author").val()
}
};
return admin.messaging().sendToTopic(topic, payload)
.then(function (response: any) {
console.log("Successfully sent message:", response);
})
.catch(function (error: any) {
console.log("Error sending message:", error);
});
});
这是我在Firebase中的数据库结构。
这里是logcat的完整Stacktrace。
TypeError: Cannot read property 'child' of undefined
at exports.sendNotification.functions.database.ref.onWrite (/srv/lib/index.js:17:41)
at cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions.js:131:23)
at /worker/worker.js:825:24
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:229:7)
sendNotification
Function execution took 286 ms, finished with status: 'error'
答案 0 :(得分:1)
请注意,onWrite()
处理程序接受具有before
和after
属性但没有data
属性的Change对象。我想这是问题的原因,请参见onWrite()
documentation。如果要获取更新的数据,请使用event.after.child('author')
而不是event.data.child('author')
。
exports.sendNotification = functions.database.ref('/article/{articleId}').onWrite(change => {
// Exit when the data is deleted.
if (!change.after.exists()) {
return null;
}
const author = change.after.child('author').val();
...
});