import { PlatformService } from './platform.service' ; import { Observable } from 'rxjs/Observable' ; import { Injectable } from '@angular/core' ; import { AngularFireDatabase } from 'angularfire2/database' ; import { makeStateKey , TransferState } from '@angular/platform-browser' ; import { database } from 'firebase' ; import { PathReference } from 'angularfire2/database/interfaces' ; @ Injectable ( ) export class FirebaseDatabaseService { constructor ( private db , private ts , private ps ) { } get < T > ( path ) { const cached = this . ts . get < T | undefined > ( this . cacheKey ( path ) , undefined ) ; return cached ? this . db . object < T > ( path ) . valueChanges ( ) . startWith ( cached ) . catch ( err => Observable . of ( undefined ) ) : this . db . object < T > ( path ) . valueChanges ( ) . catch ( err => Observable . of ( undefined ) ) ; } getList < T > ( path , queryFn ? ) { const cached = this . ts . get < T [ ] | undefined > ( this . cacheKey ( path . toString ( ) ) , undefined ) ; return cached ? this . db . list < T > ( path , queryFn ) . valueChanges ( ) . startWith ( cached as any ) . catch ( err => Observable . of ( [ ] ) ) : this . db . list < T > ( path , queryFn ) . valueChanges ( ) . catch ( err => Observable . of ( [ ] ) ) ; } getListKeyed < T > ( path , queryFn ? ) { const cached = this . ts . get < T [ ] | undefined > ( this . cacheKey ( path . toString ( ) ) , undefined ) ; return cached ? this . db . list ( path , queryFn ) . snapshotChanges ( ) . map ( a => this . keyMapper ( a ) ) . startWith ( cached as any ) . catch ( err => Observable . of ( [ ] ) ) : this . db . list ( path , queryFn ) . snapshotChanges ( ) . map ( a => this . keyMapper ( a ) ) . catch ( err => Observable . of ( [ ] ) ) ; } keyMapper ( res ) { if ( this . ps . isServer ) return res ; return res . map ( ( obj ) => { return { id : obj . key , ... obj . payload . val ( ) } ; } ) ; } getListRef < T > ( path , queryFn ? ) { return this . db . list < T > ( path , queryFn ) ; } getObjectRef < T > ( path ) { return this . db . object < T > ( path ) ; } cacheKey ( path ) { return makeStateKey < string > ( `FB.${ path }` ) ; } }