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.
- It is much more cost efficient to update aggregation doc at once (1 document write capacity vs 1 per each archived doc) when this scheduled job already know how many articles have been archived.
- If I rely only on
onDelete
trigger for aggregation doc update, a large number ofonDelete
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.
- Is there a way to suppress
onDelete
from getting called when my firebase functions deletes the documents? (vs users deleting the doc) - If I cannot suppress
onDelete
trigger, is there a way to distinguish ifonDelete
was triggered by user vs functions through firebase admin api? (e.g. usingcontext
&DocumentSnapshot
parameters that get passed into each trigger event).