Skip to content

Instantly share code, notes, and snippets.

@pc035860
Created March 9, 2014 15:19
Show Gist options
  • Select an option

  • Save pc035860/9449307 to your computer and use it in GitHub Desktop.

Select an option

Save pc035860/9449307 to your computer and use it in GitHub Desktop.
Util module for working with Firebase & angularFire
angular.module('fireUtil', ['firebase'])
.provider('fireUtil', function () {
var util, $get;
util = {
rootUrl: null,
$get: ['Firebase', function (Firebase) {
var _rootRef = util.rootUrl ? new Firebase(util.rootUrl) : null;
return {
ref: _firebaseRef,
toArray: _angularFireObjectToArray
};
/**
* Firebase reference generator
*
* Configure `rootUrl` in configuration phase:
*
* fireUtilProvider.rootUrl = 'https://...';
*
* Use it to get Firebase reference in run phase:
*
* fireUtil.ref(); // "{BASE}" reference
*
* fireUtil.ref('a', 'b', 'c'); // "{BASE}/a/b/c" reference
* fireUtil.ref(['a', 'b', 'c']); // same as above
*/
function _firebaseRef(path) {
if (!_rootRef) {
throw new Error('`rootUrl` configuration required.');
}
if (!angular.isArray(path)) {
path = Array.prototype.slice.call(arguments);
}
if (!path || path.length === 0) {
return new Firebase(util.rootUrl);
}
return _rootRef.child(path.join('/'));
}
/**
* Transform an AngularFire object (collection) to an Array object
*
* @param {AngularFire} object AngularFire object to be transformed
* @param {string} transformedKeyname key name to be attached into each array element (optional, default "$id")
* @return {array} transformed array
*/
function _angularFireObjectToArray(object, transformedKeyname) {
transformedKeyname = transformedKeyname || '$id';
var l = [];
angular.forEach(object, function (value, key) {
var update = {};
update[transformedKeyname] = key;
l.push(
angular.extend({}, value, update)
);
});
return l;
}
}]
};
return util;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment