Thursday, 13 April 2017

How to compare old and new value with Firebase Functions with .onWrite or onchange?

Lets take the following data structure:

Datastructure

Now I want to refresh the accessTokenFacebook with a Firebase Function. I tested two option:

  1. the onWrite, and the:
  2. the onChanged

The onWrite looks the best 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 happens I don'understand/can solve: when I delete a whole userUID-record (for a cleanup), the userUID-record automatically create, then only with the following path {uid}/services/facebood/accesTokenFacebook...

It seems that a deletion also triggers a onWrite.

I also tried the .onchange, but that one only triggers when there is still no accessTokenFacebook. When the change make this one, the change never triggered again.

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



via BushJopie

No comments:

Post a Comment