FCM onWrite()函数触发两次并发送两个通知?

时间:2017-07-18 21:43:56

标签: javascript ios firebase firebase-cloud-messaging google-cloud-functions

我在iOS应用中发送多个FCM通知时遇到问题。

我正在使用Firebase及其实时数据库触发功能,并且能够在将新节点添加到数据库时以及更新节点时触发Firebase代码。

问题是该函数第一次在写入时运行,它会运行两次并发送两个通知。

当节点更新时,它只运行一次,并且只发送1个通知,这是预期的行为。

下面是我的javascript代码和数据库写入的JSON结构。

任何人都可以了解为什么我的功能可能会被解雇两次吗?



var functions = require('firebase-functions');
var admin = require('firebase-admin')
var userDeviceToken = ""
var sharedUserID = ""

admin.initializeApp({
  credential: admin.credential.applicationDefault(),
  databaseURL: "https://userlocation-aba20.firebaseio.com/"
});


var payloadStart = {
  notification: {
    title: "Name of App",
    body: "Someone has shared a journey with you."
  },
};

var options = {
  priority: "high"
}

var payloadEnd = {
  notification: {
    title: "Name of App",
    body: "A shared journey has ended."
  },
};

exports.newEntry = functions.database.ref('/StartedJourneys/{fireUserID}')
  .onWrite(event => {
    const original = event.data.val()
    console.log(original.SharedWithUserID)
    console.log(original.JourneyEnded)
    console.log(event.data.changed())
    console.log(event.data.exists())
    console.log(event.data.previous)
    console.log(event.params)
    var payload = payloadStart
    if (original.JourneyEnded) {
    	payload = payloadEnd
    } 
        
    sharedUserID = original.SharedWithUserID
    console.log(sharedUserID)
    var db = admin.database()
    var ref = db.ref('/UserTokens')
    return ref.orderByKey().equalTo(sharedUserID).on("child_added", function(snapshot) {
      const deviceToken = snapshot.val()

      admin.messaging().sendToDevice(deviceToken, payload, options)
	  	.then(function(response) {
	    	console.log("Successfully sent message:", response);
	  	})
	  	.catch(function(error) {
	    	console.log("Error sending message:", error);
	  	});

    })
   
})






"StartedJourneys" : {
    "nFQhaMkjDeSHDAZCklzN7LoGGc22" : {
      "CurrentLat" : 37.543821,
      "CurrentLong" : -122.239187,
      "DestinationLat" : 37.5232217,
      "DestinationLong" : -122.2520166,
      "DestinationName" : "Nob Hill",
      "JourneyEnded" : false,
      "SharedWithUser" : "Lisa",
      "SharedWithUserID" : "mSJoMJPWWBZEnbq8X05BHwrSd2M2"
    }
  },




编辑:我已经缩小了问题的范围,希望得到答复。提前致谢!

**编辑:添加了该功能触发的2个控制台日志的屏幕截图。我应该只看到其中一个。 Firebase logs

0 个答案:

没有答案