import { makeStateKey , TransferState } from '@angular/platform-browser' ; import { Injectable , InjectionToken , NgZone } from '@angular/core' ; import { fromPromise } from 'rxjs/observable/fromPromise' ; import { fbAdminDb } from './server' ; import { database } from 'firebase-admin' ; export const FIREBASE_ADMIN_INSTANCE = new InjectionToken < string > ( 'app.fb.admin' ) ; @ Injectable ( ) export class FirebaseAdminService { constructor ( private zone , private ts ) { } public object ( path , query ? ) { return { valueChanges : ( ) => { const timeout = setTimeout ( ( ) => undefined , 10000 ) ; return fromPromise ( new Promise < any > ( ( resolve , reject ) => { this . zone . runOutsideAngular ( ( ) => { const ref = this . applyQuery ( fbAdminDb . ref ( path ) , query ) ; ref . once ( 'value' ) . then ( ( data ) => { this . zone . run ( ( ) => { this . ts . set ( makeStateKey < string > ( `FB.${ path }` ) , data . val ( ) ) ; resolve ( data . val ( ) ) ; setTimeout ( ( ) => { clearTimeout ( timeout ) ; } , 20 ) ; } ) ; } , ( err ) => { setTimeout ( ( ) => { reject ( err ) ; clearTimeout ( timeout ) ; } , 20 ) ; } ) ; } ) ; } ) ) ; } } ; } public list ( path , query ? ) { return { valueChanges : ( ) => { const timeout = setTimeout ( ( ) => undefined , 10000 ) ; return fromPromise ( new Promise < any > ( ( resolve , reject ) => { this . zone . runOutsideAngular ( ( ) => { query ( fbAdminDb . ref ( path ) ) . once ( 'value' ) . then ( ( snapshot ) => { this . zone . run ( ( ) => { const res = snapshot . val ( ) ; const projected = Object . keys ( res || { } ) . map ( key => res [ key ] ) ; this . ts . set ( makeStateKey < string > ( `FB.${ path }` ) , projected ) ; resolve ( projected ) ; setTimeout ( ( ) => { clearTimeout ( timeout ) ; } , 20 ) ; } ) ; } , ( err ) => { setTimeout ( ( ) => { reject ( err ) ; clearTimeout ( timeout ) ; } , 20 ) ; } ) ; } ) ; } ) ) ; } , snapshotChanges : ( ) => { const timeout = setTimeout ( ( ) => undefined , 10000 ) ; return fromPromise ( new Promise < any > ( ( resolve , reject ) => { this . zone . runOutsideAngular ( ( ) => { query ( fbAdminDb . ref ( path ) ) . once ( 'value' ) . then ( ( snapshot ) => { this . zone . run ( ( ) => { const res = snapshot . val ( ) ; const projected = Object . keys ( res || { } ) . map ( key => ( { ... res [ key ] , id : key } ) ) ; this . ts . set ( makeStateKey < string > ( `FB.${ path }` ) , projected ) ; resolve ( projected ) ; setTimeout ( ( ) => { clearTimeout ( timeout ) ; } , 20 ) ; } ) ; } , ( err ) => { setTimeout ( ( ) => { reject ( err ) ; clearTimeout ( timeout ) ; } , 20 ) ; } ) ; } ) ; } ) ) ; } } ; } applyQuery ( ref , query ) { for ( const n in query ) { const val = query [ n ] . getValue ? query [ n ] . getValue ( ) : query [ n ] ; switch ( n ) { case 'orderByKey' : ref = ref . orderByKey ( ) ; break ; default : if ( ! ( n in ref ) ) { break ; } ref = ref [ n ] ( val ) ; break ; } } return ref ; } }