@eixox/jetfuel-firebase-react
Version:
Our jetfuel lib to connect react to firebase
80 lines (70 loc) • 2.05 kB
JavaScript
import Xsettings from "./Xsettings.js";
/**
* Holds a reference to the firebase database;
*/
const firebaseDb = Xsettings.firebase.database();
export default class Xfirebase {
static database = firebaseDb;
static ref(name){
return firebaseDb.ref(name);
}
connect(name) {
this.name = name;
this.items = {};
this.fbref = firebaseDb.ref(name);
var dis = this;
this.fbref.on("child_added", function(data) {
var itemValue = data.val();
dis.items[data.key] = itemValue;
if (dis.onChange) dis.onChange(dis.items, data.key, itemValue);
});
this.fbref.on("child_changed", function(data) {
var itemValue = data.val();
dis.items[data.key] = itemValue;
if (dis.onChange) dis.onChange(dis.items, data.key, itemValue);
});
this.fbref.on("child_removed", function(data) {
var oldValue = dis.items[data.key];
delete dis.items[data.key];
if (dis.onChange) dis.onChange(dis.items, data.key, oldValue);
});
}
disconnect() {
if (this.fbref) this.fbref.off();
this.items = {};
this.fbref = null;
}
set(key, value) {
firebaseDb.ref(key).set(value);
}
push(collection, value) {
return firebaseDb.ref(collection).push(value).key;
}
first(key) {
return firebaseDb
.ref(key)
.once("value")
.then(function(snapshot) {
return snapshot.val();
});
}
/**
* Deletes an item from the database with the specified key;
* @param {*} key
*/
delete(key) {
return firebaseDb.ref(key).remove();
}
/**
* Iterates over the items array and produces an array with the resulting calls to fn;
* Use the "caller" parameter to give meaning to the "this" keyword inside your function;
* For example, calling map (function(){}, myObject) will set this=myObject inside function();
* @param {*} fn
* @param {*} caller
*/
map(fn, caller) {
return Object.keys(this.items).map(function(key) {
return fn.call(caller, this.items[key], key);
}, this);
}
}