-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathangularfire2.ts
212 lines (189 loc) · 8.45 KB
/
angularfire2.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import { InjectionToken, NgZone } from '@angular/core';
import { isPlatformServer } from '@angular/common';
import { Observable, Subscription, SchedulerLike, SchedulerAction, queueScheduler, Operator, Subscriber, TeardownLogic, asyncScheduler } from 'rxjs';
import { subscribeOn, observeOn, tap, share } from 'rxjs/operators';
// Put in database.ts when we drop database-depreciated
// SEMVER drop RealtimeDatabaseURL in favor of DATABASE_URL in next major
export const RealtimeDatabaseURL = new InjectionToken<string>('angularfire2.realtimeDatabaseURL');
export const DATABASE_URL = RealtimeDatabaseURL;
function noop() { }
/**
* Schedules tasks so that they are invoked inside the Zone that is passed in the constructor.
*/
export class ɵZoneScheduler implements SchedulerLike {
constructor(private zone: any, private delegate: any = queueScheduler) { }
now() {
return this.delegate.now();
}
schedule(work: (this: SchedulerAction<any>, state?: any) => void, delay?: number, state?: any): Subscription {
const targetZone = this.zone;
// Wrap the specified work function to make sure that if nested scheduling takes place the
// work is executed in the correct zone
const workInZone = function (this: SchedulerAction<any>, state: any) {
targetZone.runGuarded(() => {
work.apply(this, [state]);
});
}
// Scheduling itself needs to be run in zone to ensure setInterval calls for async scheduling are done
// inside the correct zone. This scheduler needs to schedule asynchronously always to ensure that
// firebase emissions are never synchronous. Specifying a delay causes issues with the queueScheduler delegate.
return this.delegate.schedule(workInZone, delay, state)
}
}
export class ɵBlockUntilFirstOperator<T> implements Operator<T, T> {
private task: MacroTask | null = null;
constructor(private zone: any) { }
call(subscriber: Subscriber<T>, source: Observable<T>): TeardownLogic {
const unscheduleTask = this.unscheduleTask.bind(this);
this.task = this.zone.run(() => Zone.current.scheduleMacroTask('firebaseZoneBlock', noop, {}, noop, noop));
return source.pipe(
tap(unscheduleTask, unscheduleTask, unscheduleTask)
).subscribe(subscriber).add(unscheduleTask);
}
private unscheduleTask() {
if (this.task != null && this.task.state === 'scheduled') {
this.task.invoke();
this.task = null;
}
}
}
export class ɵAngularFireSchedulers {
public readonly outsideAngular: ɵZoneScheduler;
public readonly insideAngular: ɵZoneScheduler;
constructor(public ngZone: NgZone) {
this.outsideAngular = ngZone.runOutsideAngular(() => new ɵZoneScheduler(Zone.current));
this.insideAngular = ngZone.run(() => new ɵZoneScheduler(Zone.current, asyncScheduler));
}
}
/**
* Operator to block the zone until the first value has been emitted or the observable
* has completed/errored. This is used to make sure that universal waits until the first
* value from firebase but doesn't block the zone forever since the firebase subscription
* is still alive.
*/
export function ɵkeepUnstableUntilFirstFactory(
schedulers: ɵAngularFireSchedulers,
platformId: Object
) {
return function keepUnstableUntilFirst<T>(obs$: Observable<T>): Observable<T> {
if (isPlatformServer(platformId)) {
obs$ = obs$.lift(
new ɵBlockUntilFirstOperator(schedulers.ngZone)
);
}
return obs$.pipe(
// Run the subscribe body outside of Angular (e.g. calling Firebase SDK to add a listener to a change event)
subscribeOn(schedulers.outsideAngular),
// Run operators inside the angular zone (e.g. side effects via tap())
observeOn(schedulers.insideAngular)
// This isn't working correctly #2309, #2314, #2312
// share()
);
}
}
// SEMVER: drop v6, here for compatibility
export const runOutsideAngular = (zone: NgZone) => <T>(obs$: Observable<T>): Observable<T> => {
return new Observable<T>(subscriber => {
return zone.runOutsideAngular(() => {
runInZone(zone)(obs$).subscribe(subscriber);
});
});
}
// SEMVER: drop v6, here for compatibility
export const runInZone = (zone: NgZone) => <T>(obs$: Observable<T>): Observable<T> => {
return new Observable<T>(subscriber => {
return obs$.subscribe(
value => zone.run(() => subscriber.next(value)),
error => zone.run(() => subscriber.error(error)),
() => zone.run(() => subscriber.complete()),
);
});
}
// SEMVER: drop v6, here for compatibility
export class FirebaseZoneScheduler {
constructor(public zone: NgZone, private platformId: Object) {}
schedule(...args: any[]): Subscription {
return <Subscription>this.zone.runGuarded(function() { return queueScheduler.schedule.apply(queueScheduler, args)});
}
keepUnstableUntilFirst<T>(obs$: Observable<T>) {
if (isPlatformServer(this.platformId)) {
return new Observable<T>(subscriber => {
const noop = () => {};
const task = Zone.current.scheduleMacroTask('firebaseZoneBlock', noop, {}, noop, noop);
obs$.subscribe(
next => {
if (task.state === 'scheduled') { task.invoke() };
subscriber.next(next);
},
error => {
if (task.state === 'scheduled') { task.invoke() }
subscriber.error(error);
},
() => {
if (task.state === 'scheduled') { task.invoke() }
subscriber.complete();
}
);
});
} else {
return obs$;
}
}
runOutsideAngular<T>(obs$: Observable<T>): Observable<T> {
return new Observable<T>(subscriber => {
return this.zone.runOutsideAngular(() => {
return obs$.subscribe(
value => this.zone.run(() => subscriber.next(value)),
error => this.zone.run(() => subscriber.error(error)),
() => this.zone.run(() => subscriber.complete()),
);
});
});
}
}
//SEMVER: once we move to TypeScript 3.6, we can use these to build lazy interfaces
/*
type FunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? K : never }[keyof T];
type PromiseReturningFunctionPropertyNames<T> = { [K in FunctionPropertyNames<T>]: ReturnType<T[K]> extends Promise<any> ? K : never }[FunctionPropertyNames<T>];
type NonPromiseReturningFunctionPropertyNames<T> = { [K in FunctionPropertyNames<T>]: ReturnType<T[K]> extends Promise<any> ? never : K }[FunctionPropertyNames<T>];
type NonFunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? never : K }[keyof T];
export type PromiseProxy<T> = { [K in NonFunctionPropertyNames<T>]: Promise<T[K]> } &
{ [K in NonPromiseReturningFunctionPropertyNames<T>]: (...args: Parameters<T[K]>) => Promise<ReturnType<T[K]>> } &
{ [K in PromiseReturningFunctionPropertyNames<T> ]: (...args: Parameters<T[K]>) => ReturnType<T[K]> };
*/
// DEBUG quick debugger function for inline logging that typescript doesn't complain about
// wrote it for debugging the ɵlazySDKProxy, commenting out for now; should consider exposing a
// verbose mode for AngularFire in a future release that uses something like this in multiple places
// usage: () => log('something') || returnValue
// const log = (...args: any[]): false => { console.log(...args); return false }
// The problem here are things like ngOnDestroy are missing, then triggering the service
// rather than dig too far; I'm capturing these as I go.
const noopFunctions = ['ngOnDestroy'];
// INVESTIGATE should we make the Proxy revokable and do some cleanup?
// right now it's fairly simple but I'm sure this will grow in complexity
export const ɵlazySDKProxy = (klass: any, observable: Observable<any>, zone: NgZone) => {
return new Proxy(klass, {
get: (_, name:string) => zone.runOutsideAngular(() => {
if (klass[name]) { return klass[name] }
if (noopFunctions.includes(name)) { return () => {} }
let promise = observable.toPromise().then(mod => {
const ret = mod && mod[name];
// TODO move to proper type guards
if (typeof ret == 'function') {
return ret.bind(mod);
} else if (ret && ret.then) {
return ret.then((res:any) => zone.run(() => res));
} else {
return zone.run(() => ret);
}
});
// recurse the proxy
return new Proxy(() => undefined, {
get: (_, name) => promise[name],
// TODO handle callbacks as transparently as I can
apply: (self, _, args) => promise.then(it => it && it(...args))
}
)
})
})
};