Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare old and new value with Cloud Functions for Firebase 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?

like image 530
Johan Walhout Avatar asked Apr 13 '17 17:04

Johan Walhout


People also ask

Which function is used for users to listen monitor for changes in the Firebase?

Set the event handler Functions let you handle Realtime Database events at two levels of specificity; you can listen for specifically for only creation, update, or deletion events, or you can listen for any change of any kind to a path.

What is the difference between cloud run and cloud function?

Cloud Functions lets you deploy snippets of code (functions) written in a limited set of programming languages, while Cloud Run lets you deploy container images using the programming language of your choice.

Which type of trigger is bound while creating cloud function in the lab?

Triggers supported in Cloud Functions (2nd gen) All event-driven functions in Cloud Functions (2nd gen) use Eventarc for event delivery. In Cloud Functions (2nd gen), Pub/Sub triggers and Cloud Storage triggers are implemented as particular types of Eventarc triggers.


1 Answers

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
});
like image 153
Rbar Avatar answered Oct 20 '22 18:10

Rbar