Cloud Functions for Firebase database onWrite triggered twice

空扰寡人 提交于 2019-12-05 16:34:01

This is a common mistake. You are writing back into the same database location (by removing the data) that was matched when the function first triggered. This means that removal will be triggering the function again to handle that second change. This is currently the expected behavior.

You will need to come up with a way to detect that the second write happened in response to the removal of data. Also, you are currently doing too much work in your function. There's no need to read the value of the database at '/notification/message/{recipientUid}/{senderUid}' - it is already being delivered to you in the event that's passed to the function. Be sure to read the docs about database triggers. You can know if the function was triggered a second time by examining the event data and returning early if it's null, which means it was removed.

Also, you don't need Promise.all() if you are dealing with a single promise. Just use then() on that single promise to continue processing, or return that single promise from then().

You might want to look at some of the sample code that shows database triggers.

In case someone is still confused about this, as of firebase-functions v0.5.9 ; you can use onCreate(), onUpdate() or onDelete(). Just make sure your firebase-functions version is updated which you can do so by going in your functions directory and run

npm install --save firebase-functions 

Also, it has been addressed in firebase documentation and sample as well that if you are using onWrite(), as Doug has explained above, the function will be triggered for all events at that node, i.e, write; update or delete. So you should check to make sure your function doesn't get stuck in a loop. Something like:

   //if data is not new 
    if (event.data.previous.exists()) {return}
    // Exit when the data is deleted; needed cuz after deleting the node this function runs once more.
    if (!event.data.exists()) {return}

Cheers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!