gpt4 book ai didi

ios - 无法在 Firebase 函数中读取 null 的属性

转载 作者:行者123 更新时间:2023-11-28 19:31:13 25 4
gpt4 key购买 nike

我正在向在 Firebase 消息传递中订阅特定主题的用户发送推送通知。一切正常,但在消息发出后,我从 event.data.adminRef 中删除了值,我在 Firebase Functions 日志中收到此错误消息:

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);
});
});

这是什么意思?谢谢!

最佳答案

当你在发送消息后删除消息数据时,删除相当于写入一个空值,触发你的函数再次运行,这次是空数据。您需要在顶部添加一个空数据检查,以短路第二次调用:

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);
});

关于ios - 无法在 Firebase 函数中读取 null 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44458849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com