onwrite functions firestore example deploy create firebase firebase-database google-cloud-functions

firebase - functions - firestore triggers



Funciones en la nube para Firebase OnWrite (2)

Entiendo que las funciones de Firebase proporcionan un mejor método:

El método es verificar si existe un evento previo. Si es así, no haga nada y devuelva otro trabajo, haga su trabajo ... Además, puede verificar si el artículo se está eliminando.

if (event.data.previous.exists()) { return; } // Exit when the data is deleted. if (!event.data.exists()) { return; }

Este es un ejemplo completo de la documentación de firebase .

exports.makeUppercase = functions.database.ref(''/messages/{pushId}/original'') .onWrite(event => { // Only edit data when it is first created. if (event.data.previous.exists()) { return; } // Exit when the data is deleted. if (!event.data.exists()) { return; } // Grab the current value of what was written to the Realtime Database. const original = event.data.val(); console.log(''Uppercasing'', event.params.pushId, original); const uppercase = original.toUpperCase(); // You must return a Promise when performing asynchronous tasks inside a Functions such as // writing to the Firebase Realtime Database. // Setting an "uppercase" sibling in the Realtime Database returns a Promise. return event.data.ref.parent.child(''uppercase'').set(uppercase);

Estoy mirando las Nuevas Funciones de la Nube para Firebase y dice que al hacer una OnWrite debes tener cuidado de no guardar datos en el mismo Niño. (que disparará el gatillo nuevamente).

Así que estoy tratando de averiguar, ¿cómo puedo establecer una fecha de modificación en un registro?


El problema no es que no pueda o no deba cambiar los datos, sino que debe protegerse contra ciclos infinitos. Por ejemplo, establecer una marca de tiempo podría volver a disparar la función que establecería la marca de tiempo que reactivaría ... y así sucesivamente.

Lo que puede hacer, sin embargo, es proteger su código asegurándose de marcar el estado de una manera idempotente para que el mismo código no se vuelva a disparar. Por ejemplo:

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 }); });