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

Posted

技术标签:

【中文标题】无法在 Firebase 函数中读取 null 的属性【英文标题】:Cannot read property of null in Firebase Functions 【发布时间】:2017-06-09 13:16:34 【问题描述】:

我正在向订阅 Firebase Messaging 中某个主题的用户发送推送通知。一切正常,但在消息发出后,我从 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);
     );
);

这是什么意思?谢谢!

【问题讨论】:

【参考方案1】:

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

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

【讨论】:

以上是关于无法在 Firebase 函数中读取 null 的属性的主要内容,如果未能解决你的问题,请参考以下文章

TypeError:无法读取 null 的属性“uid”

角度错误:无法读取 null 的属性(读取“控件”)

firebase云函数错误TypeError:无法读取未定义的属性“子”

无法从 Firebase 读取用户数据

Firebase 函数环境变量无法读取未定义的属性

firebase 云函数无法读取未定义的属性“ref”