Sunday, July 19, 2015

Using Firebase in an Angular Application

I've done a fair amount with Firebase lately and I've learned a thing or two.  Firebase is a non-relational real-time database which makes it perfect for applications that need some form of data stream. Essentially you take objects and shove them into storage.  The most important thing to remember when working with a non-relational store is that Denormalizing Your Data is Normal.

In my application I also used Angular, so I pulled in the AngularFire library which provides some great helpers.  In my app I abstracted all the Firebase calls out into a service which is inject into my angular controller.  Firebase is designed for high IO situations, in my application Firebase is really overkill.  The app could have used a relational store...  That said Firebase has worked very well and there are few concepts you need to grasp to begin using it in an application.  One of the big advantages has been that a simple email authentication based security model is built into the Firebase API. 

Firebase uses the concept of $priority which is similar to the concept of a indexed field in SQL.  A $priority can be a string or a number, and can then be used to query data later on.  In my application in most cases I wanted to retrieve data based on the logged in user.  I used email address as the priority, and then was able to filter data by user.  The following shows a query that implies orderByPriority.  

var gameList = $firebaseArray(ref.startAt(email).endAt(email));

This shows that Firebase has a notion of a queries, which is great.  However, it pays to note that while there are several ways to order and limit the data returned, you can't combine logic to filter down subsets of data.  The queries section of the documentation does a pretty thorough job of explaining. After retrieving your initial results further, filtering must be done client side.  For example below is a function that returns games in a date range.  

function getGameListByCreatedOnDate(startDate, endDate){
    return $firebaseArray(ref.orderByChild("createdOn").startAt(startDate).endAt(endDate));

Because I've ordered that data by a child field 'createdOn', I can't apply an additional orderByPriority method that limits the results to just the logged in users games. In this case I need to perform that additional operation after returning the results.  

No comments:

Post a Comment