我向在Firebase Messaging中订阅某个主题的用户发送推送通知。一切正常但在邮件发出后我从event.data.adminRef
删除了值我在Firebase功能日志中收到此错误消息:
TypeError: Cannot read property 'receiverId' of null
at exports.sendNotification.ref.onWrite.event (/user_code/index.js:24:38)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:35:20
at process._tickDomainCallback (internal/process/next_tick.js:129:7)
通知功能:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var ref = functions.database.ref('/notificationRequests/{notificationId}')
exports.sendNotification = ref.onWrite(event => {
var notificationId = event.params.notificationId;
var notificationRequest = event.data.val();
console.log(notificationRequest);
var receiverId = notificationRequest.receiverId;
var message = notificationRequest.message
var data = notificationRequest.data
// The topic name can be optionally prefixed with "/topics/".
var topic = '/topics/user_' + receiverId;
// See the "Defining the message payload" section below for details
// on how to define a message payload.
var payload = {
notification: {
body: message,
sound: 'default'
},
data: { data }
};
var options = {
priority: "high",
contentAvailable: true
};
// Send a message to devices subscribed to the provided topic.
admin.messaging().sendToTopic(topic, payload, options)
.then(function(response) {
// See the MessagingTopicResponse reference documentation for the
// contents of response.
console.log("Successfully sent message:", response);
return event.data.adminRef.remove();
})
.catch(function(error) {
console.log("Error sending message:", error);
});
});
这是什么意思?谢谢!
答案 0 :(得分:3)
当您在发送消息后删除消息数据时,删除(相当于写入空值)会触发您的函数再次运行,这次使用空数据。您需要在顶部添加一个空数据检查,以便将第二次调用短路:
if (!notificationRequest) {
return;
}
您还需要返回sendToTopic().then()
代码返回的Promise。这可确保您的云功能保持活动状态,直到发送消息和删除数据的异步处理完成为止。
// return added
return admin.messaging().sendToTopic(topic, payload, options)
.then(function(response) {
// See the MessagingTopicResponse reference documentation for the
// contents of response.
console.log("Successfully sent message:", response);
return event.data.adminRef.remove();
})
.catch(function(error) {
console.log("Error sending message:", error);
});