-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathdatabase.js
436 lines (377 loc) · 16.3 KB
/
database.js
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
// @flow
import { NativeModules, NativeEventEmitter } from 'react-native';
import invariant from 'invariant';
import type {
EventType,
DataSnapshotDescriptor,
DataSnapshot as DataSnapshotType,
DatabaseReference as DatabaseReferenceType,
DatabaseReferenceDescriptor,
Query as QueryType,
Priority,
App,
} from './types';
const NativeFirebaseBridgeDatabase = NativeModules.FirebaseBridgeDatabase;
export class DataSnapshot {
parentPromise:Promise<DataSnapshotDescriptor>;
constructor(data:DataSnapshotDescriptor | Promise<DataSnapshotDescriptor>) {
this.parentPromise = Promise.resolve(data);
}
child(path:string) : DataSnapshot {
const promise = this.parentPromise.then(({ uuid }) =>
NativeFirebaseBridgeDatabase.snapshotChild(uuid, path)
);
return new DataSnapshot(promise);
}
hasChild(path:string) : Promise<boolean> {
return this.parentPromise.then(({ uuid }) =>
NativeFirebaseBridgeDatabase.snapshotHasChild(uuid, path));
}
hasChildren() {
return this.parentPromise.then(({ hasChildren }) => hasChildren);
}
exists() {
return this.parentPromise.then(({ exists }) => exists);
}
numChildren() {
return this.parentPromise.then(({ childrenCount }) => childrenCount);
}
val() : Promise<any> {
return this.parentPromise.then(({ uuid }) =>
NativeFirebaseBridgeDatabase.snapshotValue(uuid));
}
key() : Promise<any> {
return this.parentPromise.then(({ uuid }) =>
NativeFirebaseBridgeDatabase.snapshotKey(uuid));
}
exportVal() : Promise<any> {
return this.parentPromise.then(({ uuid }) =>
NativeFirebaseBridgeDatabase.snapshotExportValue(uuid));
}
getPriority() : Promise<Priority> {
return this.parentPromise.then(({ priority }) => priority);
}
/**
* Fire callback for each child. The callback should return a Promise that resolves
* (or rejects) when you are finished with the snapshot. This is done so the snapshot
* can be released. If the promise resolves to boolean false then iteration will
* terminate and no further callbacks will be triggered. eg.
* snapshot.forEach(async (snapshot) => {
* // ... whatever
* if (terminalCondition) {
* return false;
* }
* })
*/
forEach(cb:(snapshot:DataSnapshotType) => Promise<?boolean>) : Promise<void> {
const wrapCb = (data:DataSnapshotDescriptor) : Promise<?boolean> => {
const snapshot:DataSnapshotType = new DataSnapshot(data);
const promise = cb(snapshot);
invariant(promise && typeof promise.then == 'function',
'DataSnapshot.forEach callbacks should return a promise so we know when ' +
'you are done with snapshots. This is necessary as all interaction ' +
'with the native modules is async so we cache snapshots and manually ' +
'release them.'
);
const release = () => NativeFirebaseBridgeDatabase.releaseSnapshot(data.uuid);
if (promise && promise.then) {
promise.then(release, e => {
release();
throw e;
});
}
return promise;
};
return this.parentPromise.then(({ uuid }) =>
NativeFirebaseBridgeDatabase.snapshotChildren(uuid).then(async (children = []) => {
let terminated = false;
for (const child:DataSnapshotDescriptor of children) {
if (terminated) {
NativeFirebaseBridgeDatabase.releaseSnapshot(child.uuid);
continue;
}
const result = await wrapCb(child);
// Boolean true indicates we should stop iterating now.
// Flag for termination but continue iterating to release remaining snapshots.
if (result === true) {
terminated = true;
}
}
}));
}
}
const eventListenersById = {};
const databaseEmitter = new NativeEventEmitter(NativeFirebaseBridgeDatabase);
databaseEmitter.addListener('databaseOn', data => {
const { id, snapshot, error } = data;
if (eventListenersById[id]) {
const { listener, cancelCallback } = eventListenersById[id];
if (!error) {
listener(snapshot);
} else {
if (cancelCallback) {
cancelCallback(new Error(error));
}
}
}
});
export class Query {
app:App;
parentPromise: Promise<DatabaseReferenceDescriptor>;
query:Array<Array<any>>;
constructor(
app:App,
parentPromise:Promise<DatabaseReferenceDescriptor>,
query:Array<Array<any>> = []) {
this.app = app;
// Wait on app to be ready to we can guarantee name is set
this.parentPromise = Promise.all([parentPromise, app.ready()]).then(([data]) => data);
this.query = query;
}
startAt(value:number|string|boolean|null, key:?string) : QueryType {
const q = ['startAt', value];
if (key != null) {
q.push(key);
}
return new Query(this.app, this.parentPromise, [...this.query, q]);
}
endAt(value:number|string|boolean|null, key:?string) : QueryType {
const q = ['endAt', value];
if (key != null) {
q.push(key);
}
return new Query(this.app, this.parentPromise, [...this.query, q]);
}
equalTo(value:number|string|boolean|null, key:?string) : QueryType {
const q = ['equalTo', value];
if (key != null) {
q.push(key);
}
return new Query(this.app, this.parentPromise, [...this.query, q]);
}
limitToFirst(limit:number) : QueryType {
return new Query(this.app, this.parentPromise, [...this.query, ['limitToFirst', limit]]);
}
limitToLast(limit:number) : QueryType {
return new Query(this.app, this.parentPromise, [...this.query, ['limitToLast', limit]]);
}
/**
* Subscribe to an event.
* @return {Function} a function that will unsubscribe from this event
*/
on(eventType:EventType,
cb:((snapshot:DataSnapshotType) => Promise<void>),
cancelCallback:((error:Error) => void) = null
) : () => void {
const p = this.parentPromise.then(
({ locationUrl }) => NativeFirebaseBridgeDatabase.on(
this.app.name, locationUrl, eventType, this.query))
.then(uniqueEventName => {
// We receive a string back from the native module that is a unique
// event name just for this event registration. An event with this name
// will be emitted for this registration. This is cached on the native
// side with the event registration handle so we can unsubscribe as
// needed.
const listener = (data:DataSnapshotDescriptor) => {
// Snapshot's are cached on the native side so we can perform further
// queries on them. Because of this we need a way to release the
// snapshot once we are done with them. We do this by returning a
// promise which, when it resolves (or rejects), causes the snapshot
// to be released on the native. The most convenient way to do this
// is to simply define your callback as async:
// ref.on(async (snapshot) => {
// // this now automatically returns a promise
// })
const snapshot:DataSnapshotType = new DataSnapshot(data);
const promise = cb(snapshot);
invariant(promise && typeof promise.then == 'function',
'DatabaseReference listeners should return a promise so we know when ' +
'you are done with snapshots. This is necessary as all interaction ' +
'with the native modules is async so we cache snapshots and manually ' +
'release them.'
);
const release = () => NativeFirebaseBridgeDatabase.releaseSnapshot(data.uuid);
if (promise && promise.then) {
promise.then(release, e => {
release();
throw e;
});
}
};
eventListenersById[uniqueEventName] = { listener, cancelCallback };
return () => {
NativeFirebaseBridgeDatabase.off(uniqueEventName);
delete eventListenersById[uniqueEventName];
};
}, error => {
if (cancelCallback) {
cancelCallback(error);
}
});
return () => {
p.then(unsubscribe => unsubscribe());
};
}
once(eventType:EventType,
cb:((snapshot:DataSnapshotType) => Promise<void>),
cancelCallback:((error:Error) => void) = null
) : () => void {
const p = this.parentPromise.then(
({ locationUrl }) => NativeFirebaseBridgeDatabase.once(
this.app.name, locationUrl, eventType, this.query))
.then(uniqueEventName => {
// We receive a string back from the native module that is a unique
// event name just for this event registration. An event with this name
// will be emitted for this registration. This is cached on the native
// side with the event registration handle so we can unsubscribe as
// needed.
const listener = (data:DataSnapshotDescriptor) => {
// Snapshot's are cached on the native side so we can perform further
// queries on them. Because of this we need a way to release the
// snapshot once we are done with them. We do this by returning a
// promise which, when it resolves (or rejects), causes the snapshot
// to be released on the native. The most convenient way to do this
// is to simply define your callback as async:
// ref.on(async (snapshot) => {
// // this now automatically returns a promise
// })
const snapshot:DataSnapshotType = new DataSnapshot(data);
const promise = cb(snapshot);
invariant(promise && typeof promise.then == 'function',
'DatabaseReference listeners should return a promise so we know when ' +
'you are done with snapshots. This is necessary as all interaction ' +
'with the native modules is async so we cache snapshots and manually ' +
'release them.'
);
const release = () => NativeFirebaseBridgeDatabase.releaseSnapshot(data.uuid);
if (promise && promise.then) {
promise.then(release, e => {
release();
throw e;
});
}
};
eventListenersById[uniqueEventName] = { listener, cancelCallback };
return () => {
delete eventListenersById[uniqueEventName];
};
});
return () => {
p.then(unsubscribe => unsubscribe());
};
}
orderByChild(path:string) : QueryType {
return new Query(this.app, this.parentPromise, [...this.query, ['orderByChild', path]]);
}
orderByKey() : QueryType {
return new Query(this.app, this.parentPromise, [...this.query, ['orderByKey']]);
}
orderByPriority() : QueryType {
return new Query(this.app, this.parentPromise, [...this.query, ['orderByPriority']]);
}
orderByValue() : QueryType {
return new Query(this.app, this.parentPromise, [...this.query, ['orderByValue']]);
}
toString() : Promise<string> {
return this.parentPromise.then(({ locationUrl }) => locationUrl);
}
}
export class DatabaseReference extends Query {
child(pathString:string) : DatabaseReferenceType {
const promise = this.parentPromise.then(
({ locationUrl }) => NativeFirebaseBridgeDatabase.child(
this.app.name, locationUrl, pathString));
return new DatabaseReference(this.app, promise);
}
push() : DatabaseReferenceType {
const promise = this.parentPromise.then(
({ locationUrl }) => NativeFirebaseBridgeDatabase.push(this.app.name, locationUrl));
return new DatabaseReference(this.app, promise);
}
setValue(value:any) : Promise<void> {
// We wrap value in array for easier handling on Android.
// See FirebridgeDatabase.java setValue()
return this.parentPromise.then(
({ locationUrl }) => NativeFirebaseBridgeDatabase.setValue(
this.app.name, locationUrl, [value]));
}
update(value:{ [key:string]: any }) : Promise<void> {
return this.parentPromise.then(
({ locationUrl }) => NativeFirebaseBridgeDatabase.update(
this.app.name, locationUrl, value));
}
setValueWithPriority(value:any, priority:Priority) : Promise<void> {
// We wrap value in array for easier handling on Android.
// See FirebridgeDatabase.java setValue()
return this.parentPromise.then(
({ locationUrl }) => NativeFirebaseBridgeDatabase.setValueWithPriority(
this.app.name, locationUrl, [value], [priority]));
}
setPriority(priority:Priority) : Promise<void> {
// We wrap priority in array for easier handling on Android.
// See FirebridgeDatabase.java setPriority()
return this.parentPromise.then(
({ locationUrl }) => NativeFirebaseBridgeDatabase.setPriority(
this.app.name, locationUrl, [priority])
);
}
remove() : Promise<void> {
return this.parentPromise.then(
({ locationUrl }) => NativeFirebaseBridgeDatabase.removeValue(
this.app.name, locationUrl));
}
key() : Promise<string> {
return this.parentPromise.then(({ key }) => key);
}
parent() : Promise<DatabaseReference> {
return new DatabaseReference(this.app, this.parentPromise.then(
({ locationUrl }) => NativeFirebaseBridgeDatabase.parent(
this.app.name, locationUrl)));
}
root() : Promise<DatabaseReference> {
return new DatabaseReference(this.app, this.parentPromise.then(
({ locationUrl }) => NativeFirebaseBridgeDatabase.parent(
this.app.name, locationUrl)));
}
}
class Database {
static ServerValue = {
TIMESTAMP: '@@firebase/ServerValue/TIMESTAMP',
};
static enableLogging(enabled) {
NativeFirebaseBridgeDatabase.enableLogging(enabled);
}
static sdkVersion() : Promise<string> {
return NativeFirebaseBridgeDatabase.sdkVersion();
}
app: App;
constructor(app:App) {
this.app = app;
}
async goOffline() {
await this.app.ready();
NativeFirebaseBridgeDatabase.goOffline(this.app.name);
}
async goOnline() {
await this.app.ready();
NativeFirebaseBridgeDatabase.goOnline(this.app.name);
}
async setPersistenceEnabled(enabled:boolean) {
await this.app.ready();
NativeFirebaseBridgeDatabase.setPersistenceEnabled(this.app.name, enabled);
}
ref(path?:string) : DatabaseReference {
invariant(path == null || typeof path == 'string',
`If path is provided it must be a string, received ${typeof path}`
);
const ref = this.app.ready().then(
() => NativeFirebaseBridgeDatabase.ref(this.app.name, path));
return new DatabaseReference(this.app, ref);
}
refFromURL(url) : DatabaseReference {
const ref = this.app.ready().then(
() => NativeFirebaseBridgeDatabase.refFromURL(this.app.name, url));
return new DatabaseReference(this.app, ref);
}
}
export default Database;