Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloud Functions for Firebase: Increment Counter

Tags:

Is it acceptable to increment a counter with a realtime database trigger using transaction?

exports.incPostCount = functions.database.ref('/threadsMeta/{threadId}/posts') .onWrite(event => {     admin.database().ref('/analytics/postCount')     .transaction(count => {         if (count === null) {             return count = 1         } else {             return count + 1         }     }) }); 
like image 842
J. Adam Connor Avatar asked Mar 20 '17 22:03

J. Adam Connor


People also ask

How do I increment a number in firestore?

Firestore now has a specific operator for this called FieldValue. increment() . By applying this operator to a field, the value of that field can be incremented (or decremented) as a single operation on the server.

Is cloud function free in firebase?

Cloud Functions includes a perpetual free tier for invocations to allow you to experiment with the platform at no charge. Note that even for free tier usage, we require a valid billing account.

What is firestore FieldValue?

A FieldValue is a union type that may contain a primitive (like a boolean or a double), a container (e.g. an array), some simple structures (such as a Timestamp ) or some Firestore-specific sentinel values (e.g. ServerTimestamp ) and is used to write data to and read data from a Firestore database.


1 Answers

Definitely! In fact, that's exactly how it's done in this code sample, although with a few small differences:

exports.countlikechange = functions.database.ref("/posts/{postid}/likes/{likeid}").onWrite((event) => {   var collectionRef = event.data.ref.parent;   var countRef = collectionRef.parent.child('likes_count');    return countRef.transaction(function(current) {     if (event.data.exists() && !event.data.previous.exists()) {       return (current || 0) + 1;     }     else if (!event.data.exists() && event.data.previous.exists()) {       return (current || 0) - 1;     }   }); }); 

Notably, this sample handles both an increment and a decrement case depending on whether the child node is being created or deleted.

like image 198
Michael Bleigh Avatar answered Sep 28 '22 07:09

Michael Bleigh