I am using aggregation technique to keep track of aggregation data such as total number of doc, etc in Firestore.
Whenever an article
document gets created or deleted, I am using Firebase functions' trigger to update aggregation data in a separate doc.
exports.onCreateArticle = functions.firestore.document("/articles/{articleId}").onCreate((change, context) => {
// Increment a count & other aggregation data in a separate aggregation doc. This is done under transaction.
}
exports.onDeleteArticle= functions.firestore.document("/articles/{articleId}").onDelete((change, context) => {
// Decrement a count & other aggregation data in a separate aggregation doc. This is done under transaction.
}
The thing is that I also want to have a weekly/monthly scheduled firebase function that moves set of articles
into different collection (e.g. e.g. archiving process). For instance, this process deletes articles in /articles/{articleId}
path and move them to /archivedArticles/{articleId}
different path.
exports.scheduleArchive = functions.pubsub.schedule("every 7 days").onRun(async (context) => {
/// move articles from `/articles/` to /archiveArticles/` and update aggregation doc at once.
}
The problem is that while this scheduled process updates the aggregation doc and deletes articles, there are many follow up onDelete
triggers get called for each doc that got archived, and they unnecessarily attempt to update the aggregation doc which is already done by the scheduled process.
When the scheduled process kicks in, I do not want onDelete
to be triggered due to following following reasons.
onDelete
trigger for aggregation doc update, a large number of onDelete
trigger will spin up, and transactional update from the trigger to aggregation doc will likely fail. It will also result in unnecessary firebase functions call.Below are my questions.
onDelete
from getting called when my firebase functions deletes the documents? (vs users deleting the doc)onDelete
trigger, is there a way to distinguish if onDelete
was triggered by user vs functions through firebase admin api? (e.g. using context
& DocumentSnapshot
parameters that get passed into each trigger event).No. Functions are always active when they're deployed. You would have delete it to stop it from working, or send it some other signal that you build yourself.
No, user information is not available in the trigger. The best you can do is have the user write their UID to the document to find out who it was, and make sure it's correct in security rules.