1

I am learning Firebase. I have learned how to read & write to Firebase Realtime Database and how to make rules for that database. I have also read about Cloud Functions.

But I'm still confused how to write my server-side code that applies some algorithm on Firebase Realtime Database and returns it to my Android app.

Grimthorr
  • 6,856
  • 5
  • 41
  • 53
Shiv
  • 122
  • 2
  • 16
  • Can you provide us with an example of some function/algorithm that you want to perform in Cloud Functions to be returned to your app? That way we can write some example code too. – Grimthorr Nov 17 '17 at 11:31
  • @Grimthorr For example in every two minute some function is called and it modifies some data in database. And also i want to know how to implement foreign key constraint in database. I have seen many things like denormalization and testing it with queries. But i want to retrieve only required information on client side not all. – Shiv Nov 17 '17 at 16:32

2 Answers2

2

Cloud Functions

Using Cloud Functions for Firebase lets you automatically run backend code in response to events triggered by Firebase features and HTTPS requests.

If you need a function to perform work on the database when called, you could configure a HTTP trigger to do this. For example, the below Cloud Function reads the last stored number from the database (stored at /lastNumber), adds 1 (one) to it, saves it back to the database and then returns the current value:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.nextNumber = functions.https.onRequest((req, res) => {
    var ref = admin.database().ref('/lastNumber');
    ref.transaction(function(current) {
      return (current || 0) + 1;
    }, function(error, committed, snapshot) {
      var currentNumber = snapshot.val().toString();
      console.log("Generated number: ", currentNumber);
      res.status(200).send(currentNumber);
    });
});

Once deployed to Cloud Functions, you can call this function simply by visiting the HTTPS endpoint for it (where <region> is your region & <project-id> is your project ID):

https://<region>-<project-id>.cloudfunctions.net/nextNumber

There are a whole host of other examples available on the Firebase Functions Samples repository which you can browse & use.


Realtime Database

The Firebase Realtime Database is known as NoSQL which means that there are no direct relationships or foreign key constraints and therefore it is suggested that you employ a process of denormalization when storing data.

The documentation goes into detail on the best practices for structuring your data and the most important thing is to avoid nesting data, and instead flatten data structures as much as possible to create data that scales.

The basic premise here is that you want to avoid downloading all data from the database when you only need to obtain a select number of items, but likewise have the ability to link items together, much like you can in a relational database. From the documentation on data fanout:

Consider, for example, a two-way relationship between users and groups. Users can belong to a group, and groups comprise a list of users. When it comes time to decide which groups a user belongs to, things get complicated.

What's needed is an elegant way to list the groups a user belongs to and fetch only data for those groups. An index of groups can help a great deal here:

// An index to track Ada's memberships
{
  "users": {
    "alovelace": {
      "name": "Ada Lovelace",
      // Index Ada's groups in her profile
      "groups": {
         // the value here doesn't matter, just that the key exists
         "techpioneers": true,
         "womentechmakers": true
      }
    },
    ...
  },
  "groups": {
    "techpioneers": {
      "name": "Historical Tech Pioneers",
      "members": {
        "alovelace": true,
        "ghopper": true,
        "eclarke": true
      }
    },
    ...
  }
}

Duplicating of data and using indexes like this is a suggested pattern for these types of databases. That's why there are functions available that allow you to perform multi-location writes in order to simplify the denormalization process.

For example in Android, with the above database structure, you could easily insert a new user (with username testuser) and add them to the techpioneers group in a single operation:

DatabaseReference database = FirebaseDatabase.getInstance().getReference();
HashMap<String, Object> data = new HashMap<>();

// Build the new data using location paths
data.put("/users/testuser/name", "Test User");
data.put("/users/testuser/groups/techpioneers", true)
data.put("/groups/techpioneers/members/testuser", true);

// Save this new data all at once
database.updateChildren(data);

Firebase have published a number of samples, examples and code labs to help you get started.

Grimthorr
  • 6,856
  • 5
  • 41
  • 53
  • Is 'database.updateChildren(data)' a atomic transaction. – Shiv Nov 17 '17 at 17:32
  • It's atmoic, but not quite a transaction, see [this post on the Firebase blog about multi-location updates](https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html) and [this question](https://stackoverflow.com/q/17437695) for more details. – Grimthorr Nov 17 '17 at 18:13
1

Firebase is from its nature server-less meaning that all the logic of an app should be contained in the client side.

However if you believe that server side logic is imperative for your app, you may extend its functionality by using:

1) cloud functions. e.g. You upload a picture from your client app and a cloud function fires to resize the picture.

2) by using google cloud platform infrastructure.

3) by using firebase admin-sdk on your own server and creating a node.js backend.

You can check here for many useful samples regarding firebase usage and this information will help you understand more of the architecture you need to follow depending on the app you want to build.

Georgios S.
  • 229
  • 1
  • 10
  • I want to implement SQL foreign key constraint into our Firebase database json. – Shiv Nov 13 '17 at 19:59
  • 1
    As you already know firebase is a nosql database so you need to denormalize your data. I would suggest watching some very useful firecasts from David East like this one https://youtu.be/WacqhiI-g_o and refer to the firebase blog as well! https://firebase.googleblog.com/2013/04/denormalizing-your-data-is-normal.html?m=1 Follow the updated links provided in the article as well! – Georgios S. Nov 13 '17 at 20:37