| 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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335 |
2×
2×
2×
2×
2×
245×
4×
241×
241×
241×
241×
241×
241×
4×
4×
4×
4×
2×
2×
2×
245×
70×
70×
70×
73×
73×
70×
16×
16×
16×
16×
16×
16×
16×
16×
16×
16×
16×
16×
16×
46×
46×
46×
56×
46×
8×
8×
4×
18×
18×
18×
18×
18×
18×
2×
85×
85×
85×
85×
85×
85×
2×
83×
85×
93×
75×
75×
75×
75×
75×
73×
75×
75×
75×
2×
2×
2×
| /**
* @flow
*/
import { NativeEventEmitter, NativeModules } from 'react-native';
import { SharedEventEmitter } from './events';
import DataSnapshot from '../modules/database/DataSnapshot';
import DatabaseReference from '../modules/database/Reference';
import { isString, nativeToJSError } from '../utils';
type Listener = DataSnapshot => any;
type Registration = {
key: string,
path: string,
once?: boolean,
appName: string,
eventType: string,
listener: Listener,
eventRegistrationKey: string,
ref: DatabaseReference,
};
/**
* Internally used to manage firebase database realtime event
* subscriptions and keep the listeners in sync in js vs native.
*/
class SyncTree {
_nativeEmitter: NativeEventEmitter;
_reverseLookup: { [string]: Registration };
_tree: { [string]: { [string]: { [string]: Listener } } };
constructor() {
this._tree = {};
this._reverseLookup = {};
Eif (NativeModules.RNFirebaseDatabase) {
this._nativeEmitter = new NativeEventEmitter(
NativeModules.RNFirebaseDatabase
);
this._nativeEmitter.addListener(
'database_sync_event',
this._handleSyncEvent.bind(this)
);
}
}
/**
*
* @param event
* @private
*/
_handleSyncEvent(event) {
if (event.error) {
this._handleErrorEvent(event);
} else {
this._handleValueEvent(event);
}
}
/**
* Routes native database 'on' events to their js equivalent counterpart.
* If there is no longer any listeners remaining for this event we internally
* call the native unsub method to prevent further events coming through.
*
* @param event
* @private
*/
_handleValueEvent(event) {
// console.log('SyncTree.VALUE >>>', event);
const { key, eventRegistrationKey } = event.registration;
const registration = this.getRegistration(eventRegistrationKey);
Iif (!registration) {
// registration previously revoked
// notify native that the registration
// no longer exists so it can remove
// the native listeners
return NativeModules.RNFirebaseDatabase.off(key, eventRegistrationKey);
}
const { snapshot, previousChildName } = event.data;
// forward on to users .on(successCallback <-- listener
return SharedEventEmitter.emit(
eventRegistrationKey,
new DataSnapshot(registration.ref, snapshot),
previousChildName
);
}
/**
* Routes native database query listener cancellation events to their js counterparts.
*
* @param event
* @private
*/
_handleErrorEvent(event) {
// console.log('SyncTree.ERROR >>>', event);
const { code, message } = event.error;
const {
eventRegistrationKey,
registrationCancellationKey,
} = event.registration;
const registration = this.getRegistration(registrationCancellationKey);
if (registration) {
// build a new js error - we additionally attach
// the ref as a property for easier debugging
const error = nativeToJSError(code, message, { ref: registration.ref });
// forward on to users .on(successCallback, cancellationCallback <-- listener
SharedEventEmitter.emit(registrationCancellationKey, error);
// remove the paired event registration - if we received a cancellation
// event then it's guaranteed that they'll be no further value events
this.removeRegistration(eventRegistrationKey);
}
}
/**
* Returns registration information such as appName, ref, path and registration keys.
*
* @param registration
* @return {null}
*/
getRegistration(registration: string): Registration | null {
return this._reverseLookup[registration]
? Object.assign({}, this._reverseLookup[registration])
: null;
}
/**
* Removes all listeners for the specified registration keys.
*
* @param registrations
* @return {number}
*/
removeListenersForRegistrations(registrations: string | string[]): number {
Iif (isString(registrations)) {
this.removeRegistration(registrations);
SharedEventEmitter.removeAllListeners(registrations);
return 1;
}
Iif (!Array.isArray(registrations)) return 0;
for (let i = 0, len = registrations.length; i < len; i++) {
this.removeRegistration(registrations[i]);
SharedEventEmitter.removeAllListeners(registrations[i]);
}
return registrations.length;
}
/**
* Removes a specific listener from the specified registrations.
*
* @param listener
* @param registrations
* @return {Array} array of registrations removed
*/
removeListenerRegistrations(listener: () => any, registrations: string[]) {
Iif (!Array.isArray(registrations)) return [];
const removed = [];
for (let i = 0, len = registrations.length; i < len; i++) {
const registration = registrations[i];
const subscriptions = SharedEventEmitter._subscriber.getSubscriptionsForType(
registration
);
Eif (subscriptions) {
for (let j = 0, l = subscriptions.length; j < l; j++) {
const subscription = subscriptions[j];
// The subscription may have been removed during this event loop.
// its listener matches the listener in method parameters
Eif (subscription && subscription.listener === listener) {
subscription.remove();
removed.push(registration);
this.removeRegistration(registration);
}
}
}
}
return removed;
}
/**
* Returns an array of all registration keys for the specified path.
*
* @param path
* @return {Array}
*/
getRegistrationsByPath(path: string): string[] {
const out = [];
const eventKeys = Object.keys(this._tree[path] || {});
for (let i = 0, len = eventKeys.length; i < len; i++) {
Array.prototype.push.apply(
out,
Object.keys(this._tree[path][eventKeys[i]])
);
}
return out;
}
/**
* Returns an array of all registration keys for the specified path and eventType.
*
* @param path
* @param eventType
* @return {Array}
*/
getRegistrationsByPathEvent(path: string, eventType: string): string[] {
Iif (!this._tree[path]) return [];
if (!this._tree[path][eventType]) return [];
return Object.keys(this._tree[path][eventType]);
}
/**
* Returns a single registration key for the specified path, eventType, and listener
*
* @param path
* @param eventType
* @param listener
* @return {Array}
*/
getOneByPathEventListener(
path: string,
eventType: string,
listener: Function
): ?string {
Iif (!this._tree[path]) return null;
Iif (!this._tree[path][eventType]) return null;
const registrationsForPathEvent = Object.entries(
this._tree[path][eventType]
);
for (let i = 0; i < registrationsForPathEvent.length; i++) {
const registration = registrationsForPathEvent[i];
if (registration[1] === listener) return registration[0];
}
return null;
}
/**
* Register a new listener.
*
* @param parameters
* @param listener
* @return {String}
*/
addRegistration(registration: Registration): string {
const {
eventRegistrationKey,
eventType,
listener,
once,
path,
} = registration;
if (!this._tree[path]) this._tree[path] = {};
if (!this._tree[path][eventType]) this._tree[path][eventType] = {};
this._tree[path][eventType][eventRegistrationKey] = listener;
this._reverseLookup[eventRegistrationKey] = registration;
if (once) {
SharedEventEmitter.once(
eventRegistrationKey,
this._onOnceRemoveRegistration(eventRegistrationKey, listener)
);
} else {
SharedEventEmitter.addListener(eventRegistrationKey, listener);
}
return eventRegistrationKey;
}
/**
* Remove a registration, if it's not a `once` registration then instructs native
* to also remove the underlying database query listener.
*
* @param registration
* @return {boolean}
*/
removeRegistration(registration: string): boolean {
if (!this._reverseLookup[registration]) return false;
const { path, eventType, once } = this._reverseLookup[registration];
Iif (!this._tree[path]) {
delete this._reverseLookup[registration];
return false;
}
Iif (!this._tree[path][eventType]) {
delete this._reverseLookup[registration];
return false;
}
// we don't want `once` events to notify native as they're already
// automatically unsubscribed on native when the first event is sent
const registrationObj = this._reverseLookup[registration];
if (registrationObj && !once) {
NativeModules.RNFirebaseDatabase.off(registrationObj.key, registration);
}
delete this._tree[path][eventType][registration];
delete this._reverseLookup[registration];
return !!registrationObj;
}
/**
* Wraps a `once` listener with a new function that self de-registers.
*
* @param registration
* @param listener
* @return {function(...[*])}
* @private
*/
_onOnceRemoveRegistration(registration, listener) {
return (...args: any[]) => {
this.removeRegistration(registration);
listener(...args);
};
}
}
export default new SyncTree();
|