DEV Community

Akshay090
Akshay090

Posted on

1 1

A cloud function to implement a counter

To add the counter we need to append the following code in the index.js, which we created in Part-2 post, please refer it before proceeding.

Code to implement the counter

exports.genderCountFxn = functions.database
.ref("/atEvent/{date}/{id}")
.onCreate((snapshot, context) => {
// Grab the current value of what was written to the Realtime Database.
const Visitor = snapshot.val();
console.log("Inside Visitor Fxn");
console.log(Visitor);
console.log(Visitor.name);
//---------------------------------------------------
//Working gender counter
const genderCountersRef = admin
.database()
.ref(`count/${Visitor.gender}`);
return genderCountersRef
.transaction(counter_value => {
return (counter_value || 0) + 1;
})
});
//To deploy firebase deploy --only functions:genderCountFxn
exports.overallCountFxn = functions.database
.ref("/atEvent/{date}/{id}")
.onCreate((snapshot, context) => {
const Visitor = snapshot.val();
const overallCountersRef = admin
.database()
.ref(`count/overAllTotal`);
return overallCountersRef
.transaction(counter_value => {
return (counter_value || 0) + 1;
})
});
//To deploy firebase deploy --only functions:overallCountFxn
view raw index.js hosted with ❤ by GitHub

We would be creating the atEvent node in the next blog, where it would be generated when we scan the QR with the android app.

To understand the path and the code in above gist, have a look at the Realtime database.

Understanding how to get this done took an effort, so if you don't get it they feel free to ask me in comments. This code is just of few lines, but it did it job perfectly to give me a bad time 😰

No lets us move to the next and the last part of this series here.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay