Posted on

Firebase Cloud Functions pt2

firebase cloud functions

Designed by Freepik

In previous post we looked at why it’s better to use Firebase Cloud Functions instead of managing all database code on your clients. We learned how to setup and create few simple functions, let’s continue learning what we can do with Cloud Functions.


What we made in previous post was an API for creating new user and saving him to geofire. Just a simple query and user in request body. That’s it, no database code in our app. But we had to write some Retrofit stuff though. Although it’s better to do that way for most cases, it’s not the Cloud Functions feature. You could do this long time ago with Admin SDK. And what if you want to get stuff done super fast?

There’s a way to save user to geofire automatically with triggers. You just save/update him to database and server makes the rest work for you. If you don’t have Cloud Functions set up, then check this post first.  Add this code to your index.js file.

and deploy with

That’s your Android code, no Retrofit, queries or any overhead.


Now that function will be called each time you create a new user or update any of his fields. How can we optimize it? You can ether create this kind of hierarchy for your model

and listen for location

But here you’ll have to create an object field for your User model in Android. GeoLocation will do. And that’s it, now it won’t do extra geofire work when locations wan’t changed.

Or if you have a flat user model and don’t wanna change it, here’s the second way

Different Triggers

There’s many other types of triggers like Storage, Authentications… One thing is there’s definitely compromises. The more you go from client database code, the more backend code you wind up writing. And if you don’t know Node.js then you’ll have to learn it or make somebody write it.

For the most part database code is simple.

Triggers are great feature, because most of database insertions come from a simple path and then you make more and more updates to other nodes. With triggers you just make update to one node and the rest will be updated as you’d want them to.

You can get server source code here, Android here with different save user approaches. Don’t forget to subscribe, follow me on Facebook, Twitter, G+ and share with friends if you think they will benefit from it!