Firestore Counters

Firestore Counters

3 min read

First install the module in your functions directory: ``` npm i adv-firestore-functions ``` then add it to your function like so: ```typescript import { eventExists, colCounter } from 'adv-firestore-functions'; functions.firestore .document('posts/{docId}') .onWrite(async (change: any, context: any) => { // don't run if repeated function if (await eventExists(context)) { return null; } await colCounter(change, context); } ``` It handles events, and everything else. If you want to make it a universal counter for all functions: ```typescript import { eventExists, colCounter } from 'adv-firestore-functions'; functions.firestore .document('{colId}/{docId}') .onWrite(async (change: any, context: any) => { const colId = context.params.colId; // don't run if repeated function if (await eventExists(context) || colId.startsWith('_')) { return null; } await colCounter(change, context); } ``` And don't forget about Firebase Security Rules: ``` match /_counters/{document} { allow read; allow write: if false; } ``` And you use it on the front-end this way: ```typescript const collectionPath = 'path/to/collection'; const colSnap = await db.doc('_counters/' + collectionPath).get(); const count = colSnap.get('count'); ``` And, no more keeping track of the number of documents!
cloudfunction
index
counter