How to compare old and new value with cloud functions for Firebase using .onWrite or onchange?

Let's take the following data structure:

Datastructure

Now I want to update accessTokenFacebook using the Firebase function. I checked two options:

OnWrite looks better to me, but with the following function:

exports.getFacebookAccessTokenOnchange = functions.database.ref('/users/{uid}/userAccountInfo/lastLogin').onWrite(event => { const lastLogin = event.data; let dateObject = new Date(); let currentDate = dateObject.toUTCString(); return lastLogin.ref.parent.parent.child('services').child('facebook').update({'accessTokenFacebook': currentDate}); }); 

Something is happening, I don’t understand / I can decide: when I delete the entire userUID record (for cleaning), the userUID record automatically creates, and then only with the following path: {uid} / services / facebood / accesTokenFacebook ...

Removal seems to trigger onWrite as well.

I also tried .onchange, but this one only works when there is still no access to TokenFacebook. When a change does this, the change never starts again.

So, the next thing I want to do is to compare the old and the new meaning. Do you have an example? Or is there a better solution?

+5
source share
1 answer

I almost missed that it accepted the accepted answer, as it is only in the comments. All credit @Michael Bleigh.

In case someone stumbles upon this question and almost misses it, the answer will be as follows:

 exports.yourFunctionName = functions.database.ref('/somePath/anotherPath/{someVariablePath}/deeper/path').onWrite(event => { const oldValue = event.data.previous.val(); const newValue = event.data.val() }); 
+8
source

Source: https://habr.com/ru/post/1266707/


All Articles