Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Firebase to handle automatic server-side calculations?

Tags:

firebase

Perhaps my question should be restated as: how do I refactor those behaviours into CRUD, which is what Firebase excels at?

I get that CRUD works well. I also see how the Firebase declarative security model allows me to ensure proper security server-side, where it should exist.

Let's say I have a subscription service. Each time a person signs up for a service, they need to automatically have a "due" line item added to their account. In simple terms:

/users/john
/services/goodstuff

So john can sign up for goodstuff, I might let him in for 30 days without paying, but will remind him when 30 days is up, "hey, you need to pay or else you lose your subscription to goodstuff."

With a server back-end, I would POST to /services/goodstuff/members, e.g., have part of the POST handler add a "you owe" line item to john's account, ensuring that no one can join goodstuff without being marked as owing.

In a Firebase BaaS app, where those server-side logics don't exist, how would I refactor the app to get the same effective behaviour?

like image 801
deitch Avatar asked Jul 28 '13 08:07

deitch


1 Answers

Update (March 10, 2017): While the architecture I outline below is still valid and can be used to combine Firebase with any existing infrastructure, Firebase just released Cloud Functions for Firebase, which allows you to run JavaScript functions on Google's servers in response to Firebase events (such as database changes, users signing in and much more).

One potential solution (untested, sorry; but it should be the right idea):

{
  "rules": {
    "users": {
      "$user": {
        /* When they create their user record, they must write a 'due' that's
         * within the next 30 days. */
        ".write": "!data.exists() && newData.child('due').isNumber() && newData.child('due').val() < now + (30*24*60*60*1000)"
      }
    },
    "services":
      "$service": {
        /* Must be authenticated and due date must not be passed. */
        ".read": "auth != null && now < root.child('users/' + auth.id + '/due).val()" 
      }
    }
  }
}

This would require that when somebody logs in for the first time and initializes their users/ entry, they'd have to write a due date in the next 30 days. And then when accessing any service, that due date would be verified to have not passed.

That said, another option is to just spin up a tiny backend service to handle this sort of business logic. Firebase excels at protecting, storing, and synchronizing data. But if you have complicated business logic, you might want to think about spinning up a tiny backend process. Firebase has a REST api as well as Node.JS and JVM clients, so it's really easy to run your own backend code that integrates with Firebase.

like image 161
Michael Lehenbauer Avatar answered Oct 15 '22 23:10

Michael Lehenbauer