How can I trigger a function on any document change in any collection in Firestore? I want to manage createdAt and updatedAt timestamps. I have many collections and don't want to have to register the trigger for each independently. At that point I might as well just create wrapper functions for add, set, and update.
How can I register a callback that fires when any document is modified?
EDIT:
At this time (2019-08-22), I decided to just create a wrapper function to implement this functionality. The accepted answer does not maintain schema-less-ness. Based on this article, I created this upset function which manages timestamps and avoids "document does not exist" errors:
const { firestore: { FieldValue } } = require('firebase-admin')
module.exports = async function upset (doc, data = {}) {
const time = FieldValue.serverTimestamp()
const update = { updatedAt: time }
const updated = { ...data, ...update }
try {
const snapshot = await doc.get()
if (snapshot.exists) {
return doc.update(updated)
} else {
const create = { createdAt: time }
const created = { ...updated, ...create }
return doc.set(created)
}
} catch (error) {
throw error
}
}
As explained in the doc, you can use wildcards in the document path. More specifically "You may define as many wildcards as you like to substitute explicit collection or document IDs"
So, the following Cloud Function will work for documents that are under a root collection:
exports.universalFirestoreTrigger = functions.firestore
.document('{collecId}/{docId}')
.onWrite((snap, context) => {
console.log("Collection: " + context.params.collecId);
console.log("Document: " + context.params.docId);
return null;
});
If you have sub-collections, you will need to write another Cloud Function, as follows:
exports.universalFirestoreTriggerSubCollections = functions.firestore
.document('{collecId}/{docId}/{subCollecId}/{subDocId}')
.onWrite((snap, context) => {
console.log("Collection: " + context.params.collecId);
console.log("Document: " + context.params.docId);
console.log("Sub-Collection: " + context.params.subCollecId);
console.log("Sub-Collection Document: " + context.params.subDocId);
return null;
});
And so on if you have sub-sub-collections....
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