Automatic Firestore Timestamps

Automatic Firestore Timestamps

3 min read

In Firestore, sometimes you want to automatically update the createdAt and updatedAt fields. This is more accurate and prevents any security issues when done on the backend. I wrote trigger functions which accomplishes this, among other things. A Trigger Function is a function that runs on the same "Triggered Document." First install the package in your firebase functions project: ``` npm i adv-firestore-functions ``` Check for a trigger function to prevent infinite loops, and simply run the Trigger Function: ```typescript import { isTriggerFunction, TriggerFunction } from 'adv-firestore-functions'; functions.firestore.document('posts/{docId}') .onWrite(async (change: any, context: any) => { if (isTriggerFunction(change, context)) { return null; } // Trigger Function updates the same document that is Triggered await TriggerFunction(change); }); ``` The Trigger Function automatically update the dates field. This is done by default. You could also update all documents' date fields with a universal function like so: ```typescript import { isTriggerFunction, TriggerFunction } from 'adv-firestore-functions'; functions.firestore.document('{colId}/{docId}') .onWrite(async (change: any, context: any) => { const colId = context.params.colId; // ignore index collections...  if (isTriggerFunction(change, context) || colId.startsWith(_)) { return null; } // Trigger Function updates the same document that is Triggered  await TriggerFunction(change); }); ``` For more info on how this works, see the npm package. Note: While this works well, this may not be the best option for your site. Think about using firestore rules to automate dates. See here.
timestamp
triggerfunction
cloudfunction