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 ?
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.
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.
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
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With