6
votes

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?

2
functions.database.ref(...).onWrite(e => console.log(e.data.previous.val(), e.data.val())) - Michael Bleigh
@Michael, fast response :) That looks straightforward, I'll try this as soon as possible. - Johan Walhout
@Michael, Thx! I works fine. - Johan Walhout
@MichaelBleigh you should post your comment as an answer. It helped me out but I almost missed it because it was just a comment. In the meantime, I'll post an answer so others don't nearly do the same, but I'll happily take mine down if you want to post yours and take the credit! :) - Rbar

2 Answers

12
votes

UPDATE: Cloud Functions recently introduced changes to the API as noted here.

Now (>= v1.0.0)

exports.dbWrite = functions.database.ref('/path').onWrite((change, context) => {
  const beforeData = change.before.val(); // data before the write
  const afterData = change.after.val(); // data after the write
});

Before (<= v0.9.1)

exports.dbWrite = functions.database.ref('/path').onWrite((event) => {
  const beforeData = event.data.previous.val(); // data before the write
  const afterData = event.data.val(); // data after the write
});
5
votes

Now that these functions are deprecated and this is the number one search result for this subject, here is the new updated version that Cloud Functions now use.

exports.yourFunction = functions.database.ref('/path/{randomPath}/goes/here').onWrite((change, context) => {
    // Your value after the write
    const newVal = change.after.val();
    // Your value before the write
    const oldVal = change.before.val();
});