Last active
September 1, 2017 19:53
-
-
Save SpeedoPasanen/6d6559787c17a88c60cf2ddc9ca06527 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Use this instead of AngularfireDatabase in your ServerDatabaseService | |
import { Injectable, Inject, NgZone } from '@angular/core'; | |
@Injectable() | |
export class FirebaseAdminService { | |
constructor( | |
@Inject('firebaseAdmin') private admin, // An initialized instance of firebase-admin, provided from the outside | |
private zone: NgZone | |
) { } | |
public snapshot(path, query): Promise<any> { | |
let timeout = setTimeout(() => { // Give time for socket to return something before Universal exits. | |
// Timeout gets canceled when the data's in, so this line won't be reached in a normal world. | |
}, 10000); | |
return new Promise<any>((resolve, reject) => { | |
this.zone.runOutsideAngular(() => { // Out of Angular's zone so it doesn't wait for the neverending socket connection to end. | |
let ref = this.applyQuery(this.admin.database().ref(path), query); | |
ref.once('value').then(data => { | |
this.zone.run(() => { // Back in Angular's zone | |
resolve(data); | |
setTimeout(() => { | |
// Maybe getting the data will result in more components to the view that need related data. | |
// 20ms should be enough for those components to init and ask for more data. | |
clearTimeout(timeout); | |
}, 20); | |
}); | |
}, err => reject(err)); | |
}); | |
}); | |
} | |
private applyQuery(ref, query) { | |
for (var n in query) { | |
const val = query[n].getValue | |
? query[n].getValue() // BehaviorSubject | |
: query[n]; // Primitive | |
switch (n) { | |
case 'orderByKey': | |
ref = ref.orderByKey(); | |
break; | |
default: | |
if (!(n in ref)) { | |
break; | |
} | |
ref = ref[n](val); | |
break; | |
} | |
} | |
return ref; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment