2017-06-09 24 views
0

Firebase Messagingで特定のトピックを購読しているユーザーにプッシュ通知を送信しています。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) 

Notifcations機能:

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

それが何を意味するメッセージが出て送信されると、私は私が私のFirebase機能のログで、このエラーメッセージが表示されますevent.data.adminRefから値を削除した後、すべてが動作しますが?ありがとう!

答えて

2

メッセージを送信した後にメッセージデータを削除すると、null値を書き込むのと同じように削除が実行され、今度はnullデータで関数が再度実行されます。あなたは短絡に、ヌルデータの先頭に2番目の呼び出しをチェックを追加する必要があります。

if (!notificationRequest) { 
    return; 
} 

あなたはまた、あなたのsendToTopic().then()コードによって返された約束を返却する必要があります。これにより、メッセージを送信してデータを削除する非同期処理が完了するまで、クラウド機能が有効に保たれます。

// 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); 
}); 
関連する問題