Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloud Functions for Firebase OnWrite

I'm looking at the New Cloud Functions for Firebase and it says when doing an OnWrite you should be careful not to save data back to the same Child. (which will fire off the trigger again).

So I'm trying to figure out, how do I set a modification date on a record ?

like image 554
Mark Avatar asked Mar 12 '17 04:03

Mark


People also ask

What are cloud functions in Firebase?

Cloud Functions for Firebase is a serverless framework that lets you automatically run backend code in response to events triggered by Firebase features and HTTPS requests. Your JavaScript or TypeScript code is stored in Google's cloud and runs in a managed environment.

Is cloud functions free in Firebase?

Cloud Functions includes a perpetual free tier for invocations to allow you to experiment with the platform at no charge. Note that even for free tier usage, we require a valid billing account.


1 Answers

The issue isn't that you can't or shouldn't change the data, but that you need to guard against infinite loops. For instance, setting a timestamp could retrigger the function which would set the timestamp which would retrigger...and so on.

What you can do, however, is guard your code by making sure to mark the state in an idempotent way so the same code doesn't retrigger. For example:

exports.doThing = functions.database.ref('/events/{id}').onWrite(ev => {
  // prevent loops by guarding on data state
  if (ev.data.child('didThingAt').exists()) return;

  // do thing here...

  return ev.data.adminRef.update({
    didThingAt: admin.database.ServerValue.TIMESTAMP
  });
});
like image 190
Michael Bleigh Avatar answered Oct 13 '22 22:10

Michael Bleigh