-
Notifications
You must be signed in to change notification settings - Fork 7
/
firebase-utils.ts
58 lines (54 loc) · 2.16 KB
/
firebase-utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import {Observable} from 'rxjs/Rx';
declare var Firebase:FirebaseStatic;
/**
* A class that defines utility functions that help Wrap the Firebase JavaScript API.
*/
export class FirebaseUtils {
/**
* Wraps the given Firebase call in a Promise.
* When the async call returns, the Promise resolves with the callback
* arguments in an array.
* @param obj The object that the given function should be called on. This is typically your Firebase ref instance.
* @param fn The function that should be wrapped.
* @param args The Arguments that should be given to Firebase.
* @returns {Promise<any[]>}
*/
public static wrapFirebaseAsyncCall(obj:any, fn:Function, args:any[] = []):Promise<any[]> {
args = args.slice();
return new Promise((resolve, reject) => {
args.push(callback);
function callback(err) {
if (err !== null) {
reject(err);
}
else {
resolve(Array.prototype.slice.call(arguments));
}
}
fn.apply(obj, args);
});
}
/**
* Gets an observable that represents the given event name for the internal Firebase instance.
* Whenever the event is triggered by the internal Firebase instance, the Observable will resolve with the new data.
* This function is useful to map Firebase events to Observables.
* When the observable is disposed, the event listener is removed.
* @param firebase The Raw Firebase JavaScript API Object.
* @param eventName The name of the event that should be listened to.
* @returns {Observable<any>}
*/
public static wrapFirebaseEvent(firebase:Firebase, eventName:string):Observable<any[]> {
return Observable.create((observer) => {
var callback = firebase.on(eventName,
function() {
observer.next(Array.prototype.slice.call(arguments));
},
(err) => {
observer.error(err);
});
return () => {
firebase.off(eventName, callback);
};
});
}
}