My developer to-do list grows constantly and Firebase was already there for a long time.
Firebase is a cool platform that provide us with a real time database that stores JSON data and give us authentication out of the box, so we can focus on building the front-end.
But before building anything we need to wrap our head around the data model because the app will be retrieving data as it is stored, though we don’t have access to the REST API and therefore we can’t control or modify it.
This is an interesting design exercise with a big focus on denormalization, and by reading the documentation we find two ways of saving data: push()
to an array which generates a unique ID or set()
our own ID.
To create our own IDs from names, usernames, or any other string combination; I’ve been using a couple of simple AngularJS filters that I released to GitHub.
Camelize
First I created camelize to convert strings to lower camel case.
angular.module('puigcerber.camelize', []) .filter('camelize', function () { return function (input) { if (!input) { return input; } return input.replace(/[^A-Za-z0-9]+(\w|$)/g, function (_, letter) { return letter.toUpperCase(); }).replace(/^(.)/, function (_, letter) { return letter.toLowerCase(); }); }; });
Lowerize
But when I was developing an autocomplete method, combining orderByKey()
and startAt()
, I realized it would be better to have the keys in lower case, thus in a similar manner I created lowerize.
angular.module('puigcerber.lowerize', []) .filter('lowerize', function() { return function(input) { if (!input) { return input; } return input.replace(/[^A-Za-z0-9]/g, '').toLowerCase(); }; });
Usage
Although we can’t use AngularFire to set our custom IDs, we can always fallback to the JavaScript API and use it like this:
var ref = new $window.Firebase(FBURL); var user = { username: 'Puigcerber', name: 'Pablo' }; var id = $filter('lowerize')(user.username); ref.child('users').child(id).set(user);
I hope this is useful to somebody else and as always, all comments are more than welcome!
I used mongodb … And with help of webapi the rest service I used to make ajax calls and retrieve json type data as it is. ..is firebase a nosql database too ??
Yeah, it’s a NoSQL cloud database. And you retrieve data through WebSockets using their JavaScript library.
Pingback: Atomic updates with AngularFire | this.blog.name is undefined