Skip to content

Instantly share code, notes, and snippets.

@kurapatijayaram
Last active July 9, 2017 17:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kurapatijayaram/e2f97d0966bf5baac07a5aa7a0c3e77d to your computer and use it in GitHub Desktop.
Save kurapatijayaram/e2f97d0966bf5baac07a5aa7a0c3e77d to your computer and use it in GitHub Desktop.
A simple firebase angular(>2.x) module for initializing firebase app and async pipes for fetching data from firebase database.
/*
This is a simple AngularJs(>2.x) module for initializing the firebase app and async pipes for fetching data from firebase
database.
For fetching all details from particular location.
Syntax:
{{'clients/-KiAAhNT6LZMHGS9c-4g/name' | firePipeValue:'on' | async}}
{{'clients/-Ki9saJqb03SACfx89_X' | firePipeValue:'off' | async}}
Note: Dont use the above pipe for fetching list of objects
For fetching list of objects at particular location.
Syntax:
{{'testTasks' | firePipeList | async | json}}
You can also use with ngFor:
<tr *ngFor="let user of ('users' | firePipeList:'on':{limitToFirst: 3, orderByChild: 'name', equalTo: 'KURAPATI JAYARAM'});let index=index">
{{user | json}}
</tr>
*/
import { NgModule, Pipe, PipeTransform } from "@angular/core";
import * as firebase from "firebase";
import { Observable } from "rxjs/Observable";
import { Observer } from "rxjs/Observer";
export interface IFirebaseConfig{
"apiKey": string,
"authDomain": string,
"databaseURL": string,
"storageBucket": string,
"messagingSenderId": string
}
export class FirebaseQuery {
private firebaseQueryRef: firebase.database.Query;
constructor(private dataRef: string, query: Object){
//{orderByKey: true, limitToLast: 10}
this.firebaseQueryRef = firebase.database().ref(dataRef);
this._buildQuery(query);
}
public queryRef(): firebase.database.Query {
return this.firebaseQueryRef
}
private _buildQuery(query: Object){
// chain orderBy
if(query["orderByKey"]){
this._orderByKey();
}else if(query["orderByChild"]){
this._orderByChild(query["orderByChild"]);
}else if(query["orderByValue"]){
this._orderByValue();
}
//chain equalTo
if(query["equalTo"]){
this._equalTo(query["equalTo"]);
if(query["limitToFirst"]){
this._limitToFirst(query["limitToFirst"]);
}
if(query["limitToLast"]){
this._limitToLast(query["limitToLast"]);
}
return;
}
if(query["startAt"]){
this._startAt(query["startAt"]);
}
if(query["endAt"]){
this._endAt(query["endAt"]);
}
if(query["limitToFirst"]){
this._limitToFirst(query["limitToFirst"]);
}
if(query["limitToLast"]){
this._limitToLast(query["limitToLast"]);
}
}
private _orderByKey(){
this.firebaseQueryRef = this.firebaseQueryRef.orderByKey();
}
private _orderByChild(child: string){
this.firebaseQueryRef = this.firebaseQueryRef.orderByChild(child);
}
private _orderByValue(){
this.firebaseQueryRef = this.firebaseQueryRef.orderByValue();
}
private _equalTo(value: string | boolean){
this.firebaseQueryRef = this.firebaseQueryRef.equalTo(value);
}
private _limitToLast(value: number){
this.firebaseQueryRef = this.firebaseQueryRef.limitToLast(value);
}
private _limitToFirst(value: number){
this.firebaseQueryRef = this.firebaseQueryRef.limitToFirst(value);
}
private _startAt(value: any){
this.firebaseQueryRef = this.firebaseQueryRef.startAt(value);
}
private _endAt(value: any){
this.firebaseQueryRef = this.firebaseQueryRef.endAt(value);
}
}
// For fetching all details from particular location.
// Syntax:
// {{'clients/-KiAAhNT6LZMHGS9c-4g/name' | firePipeValue | async}}
// {{'clients/-Ki9saJqb03SACfx89_X' | firePipeValue | async}}
@Pipe({name: "firePipeValue"})
export class FirebasePipe implements PipeTransform {
transform(ref: string, listenType: "on" | "once"="on"): Observable<any>{
return Observable.create((observer: Observer<any>) => {
function onValue(data){
observer.next(data.val());
}
let firebaseQueryRef = new FirebaseQuery(ref, {});
if(listenType == "on"){
firebaseQueryRef.queryRef().on("value", onValue);
}else{
firebaseQueryRef.queryRef().once("value", onValue);
}
return function(){
firebaseQueryRef.queryRef().off("value", onValue);
}
});
}
}
// For fetching array of list at particular location.
// Syntax:
// {{'testTasks' | firePipeList | async | json}}
// You can also use with ngFor:
// <tr *ngFor="let user of ('users' | firePipeList:'on':{limitToFirst: 3, orderByChild: 'name', equalTo: 'KURAPATI JAYARAM'});let index=index">
// {{user | json}}
// </tr>
@Pipe({name: "firePipeList"})
export class FirebasePipeList implements PipeTransform {
transform(ref: string, listenType: "on" | "once"="once", query: Object={}): Observable<any>{
return Observable.create((observer: Observer<any>) => {
let dataArray: Object[] = [];
let firebaseQueryRef = new FirebaseQuery(ref, query);
function onChildAdded(data){
if(data){
let entity = {};
entity['key'] = data.key;
entity['value'] = data.val();
dataArray.push(entity);
observer.next(dataArray.slice());
}
}
function onChildChanged(data){
let index = dataArray.findIndex((entity) => {
return entity["key"] == data.key;
});
let changedData = {};
changedData["key"] = data.key;
changedData["value"] = data.val();
dataArray[index] = changedData;
observer.next(dataArray.slice());
}
function onChildRemoved(data){
let index = dataArray.findIndex((entity) => {
return entity["key"] == data.key;
});
dataArray.splice(index, 1);
observer.next(dataArray.slice());
}
function onceValue(data){
if(data){
let entities = data.val();
Object.keys(entities).forEach((entity) => {
let entityData = {};
entityData['key'] = entity;
entityData['value'] = entities[entity];
dataArray.push(entityData);
});
observer.next(dataArray.slice());
}
}
if(listenType == "on"){
firebaseQueryRef.queryRef().on("child_added", onChildAdded);
firebaseQueryRef.queryRef().on("child_changed", onChildChanged);
firebaseQueryRef.queryRef().on("child_removed", onChildRemoved);
}else{
firebaseQueryRef.queryRef().once("value", onceValue);
}
return function(){
if(listenType == "on"){
firebaseQueryRef.queryRef().off("child_added", onChildAdded);
firebaseQueryRef.queryRef().off("child_changed", onChildChanged);
firebaseQueryRef.queryRef().off("child_removed", onChildRemoved);
}
}
});
}
}
@NgModule({
exports: [FirebasePipeList, FirebasePipe],
declarations: [FirebasePipeList, FirebasePipe]
})
export class FirebaseConfigModule{
static init(config: IFirebaseConfig){
firebase.initializeApp(config);
return {
ngModule: FirebaseConfigModule
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment