forked from firebase/firebase-js-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReference_impl.ts
2271 lines (2135 loc) · 80.3 KB
/
Reference_impl.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
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { assert, getModularInstance, Deferred } from '@firebase/util';
import {
Repo,
repoAddEventCallbackForQuery,
repoGetValue,
repoRemoveEventCallbackForQuery,
repoServerTime,
repoSetWithPriority,
repoUpdate
} from '../core/Repo';
import { ChildrenNode } from '../core/snap/ChildrenNode';
import { Index } from '../core/snap/indexes/Index';
import { KEY_INDEX } from '../core/snap/indexes/KeyIndex';
import { PathIndex } from '../core/snap/indexes/PathIndex';
import { PRIORITY_INDEX } from '../core/snap/indexes/PriorityIndex';
import { VALUE_INDEX } from '../core/snap/indexes/ValueIndex';
import { Node } from '../core/snap/Node';
import { syncPointSetReferenceConstructor } from '../core/SyncPoint';
import { syncTreeSetReferenceConstructor } from '../core/SyncTree';
import { parseRepoInfo } from '../core/util/libs/parser';
import { nextPushId } from '../core/util/NextPushId';
import {
Path,
pathEquals,
pathGetBack,
pathGetFront,
pathChild,
pathParent,
pathToUrlEncodedString,
pathIsEmpty
} from '../core/util/Path';
import {
fatal,
MAX_NAME,
MIN_NAME,
ObjectToUniqueKey
} from '../core/util/util';
import {
isValidPriority,
validateFirebaseDataArg,
validateFirebaseMergeDataArg,
validateKey,
validatePathString,
validatePriority,
validateRootPathString,
validateUrl,
validateWritablePath
} from '../core/util/validation';
import { Change } from '../core/view/Change';
import { CancelEvent, DataEvent, EventType } from '../core/view/Event';
import {
CallbackContext,
EventRegistration,
QueryContext,
UserCallback
} from '../core/view/EventRegistration';
import {
QueryParams,
queryParamsEndAt,
queryParamsEndBefore,
queryParamsGetQueryObject,
queryParamsLimitToFirst,
queryParamsLimitToLast,
queryParamsOrderBy,
queryParamsStartAfter,
queryParamsStartAt
} from '../core/view/QueryParams';
import { Database } from './Database';
import { OnDisconnect } from './OnDisconnect';
import {
ListenOptions,
Query as Query,
DatabaseReference,
Unsubscribe,
ThenableReference
} from './Reference';
/**
* @internal
*/
export class QueryImpl implements Query, QueryContext {
/**
* @hideconstructor
*/
constructor(
readonly _repo: Repo,
readonly _path: Path,
readonly _queryParams: QueryParams,
readonly _orderByCalled: boolean
) {}
get key(): string | null {
if (pathIsEmpty(this._path)) {
return null;
} else {
return pathGetBack(this._path);
}
}
get ref(): DatabaseReference {
return new ReferenceImpl(this._repo, this._path);
}
get _queryIdentifier(): string {
const obj = queryParamsGetQueryObject(this._queryParams);
const id = ObjectToUniqueKey(obj);
return id === '{}' ? 'default' : id;
}
/**
* An object representation of the query parameters used by this Query.
*/
get _queryObject(): object {
return queryParamsGetQueryObject(this._queryParams);
}
isEqual(other: QueryImpl | null): boolean {
other = getModularInstance(other);
if (!(other instanceof QueryImpl)) {
return false;
}
const sameRepo = this._repo === other._repo;
const samePath = pathEquals(this._path, other._path);
const sameQueryIdentifier =
this._queryIdentifier === other._queryIdentifier;
return sameRepo && samePath && sameQueryIdentifier;
}
toJSON(): string {
return this.toString();
}
toString(): string {
return this._repo.toString() + pathToUrlEncodedString(this._path);
}
}
/**
* Validates that no other order by call has been made
*/
function validateNoPreviousOrderByCall(query: QueryImpl, fnName: string) {
if (query._orderByCalled === true) {
throw new Error(fnName + ": You can't combine multiple orderBy calls.");
}
}
/**
* Validates start/end values for queries.
*/
function validateQueryEndpoints(params: QueryParams) {
let startNode = null;
let endNode = null;
if (params.hasStart()) {
startNode = params.getIndexStartValue();
}
if (params.hasEnd()) {
endNode = params.getIndexEndValue();
}
if (params.getIndex() === KEY_INDEX) {
const tooManyArgsError =
'Query: When ordering by key, you may only pass one argument to ' +
'startAt(), endAt(), or equalTo().';
const wrongArgTypeError =
'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +
'endAt(), endBefore(), or equalTo() must be a string.';
if (params.hasStart()) {
const startName = params.getIndexStartName();
if (startName !== MIN_NAME) {
throw new Error(tooManyArgsError);
} else if (typeof startNode !== 'string') {
throw new Error(wrongArgTypeError);
}
}
if (params.hasEnd()) {
const endName = params.getIndexEndName();
if (endName !== MAX_NAME) {
throw new Error(tooManyArgsError);
} else if (typeof endNode !== 'string') {
throw new Error(wrongArgTypeError);
}
}
} else if (params.getIndex() === PRIORITY_INDEX) {
if (
(startNode != null && !isValidPriority(startNode)) ||
(endNode != null && !isValidPriority(endNode))
) {
throw new Error(
'Query: When ordering by priority, the first argument passed to startAt(), ' +
'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +
'(null, a number, or a string).'
);
}
} else {
assert(
params.getIndex() instanceof PathIndex ||
params.getIndex() === VALUE_INDEX,
'unknown index type.'
);
if (
(startNode != null && typeof startNode === 'object') ||
(endNode != null && typeof endNode === 'object')
) {
throw new Error(
'Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +
'equalTo() cannot be an object.'
);
}
}
}
/**
* Validates that limit* has been called with the correct combination of parameters
*/
function validateLimit(params: QueryParams) {
if (
params.hasStart() &&
params.hasEnd() &&
params.hasLimit() &&
!params.hasAnchoredLimit()
) {
throw new Error(
"Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use " +
'limitToFirst() or limitToLast() instead.'
);
}
}
/**
* @internal
*/
export class ReferenceImpl extends QueryImpl implements DatabaseReference {
/** @hideconstructor */
constructor(repo: Repo, path: Path) {
super(repo, path, new QueryParams(), false);
}
get parent(): ReferenceImpl | null {
const parentPath = pathParent(this._path);
return parentPath === null
? null
: new ReferenceImpl(this._repo, parentPath);
}
get root(): ReferenceImpl {
let ref: ReferenceImpl = this;
while (ref.parent !== null) {
ref = ref.parent;
}
return ref;
}
}
/**
* A `DataSnapshot` contains data from a Database location.
*
* Any time you read data from the Database, you receive the data as a
* `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach
* with `on()` or `once()`. You can extract the contents of the snapshot as a
* JavaScript object by calling the `val()` method. Alternatively, you can
* traverse into the snapshot by calling `child()` to return child snapshots
* (which you could then call `val()` on).
*
* A `DataSnapshot` is an efficiently generated, immutable copy of the data at
* a Database location. It cannot be modified and will never change (to modify
* data, you always call the `set()` method on a `Reference` directly).
*/
export class DataSnapshot {
/**
* @param _node - A SnapshotNode to wrap.
* @param ref - The location this snapshot came from.
* @param _index - The iteration order for this snapshot
* @hideconstructor
*/
constructor(
readonly _node: Node,
/**
* The location of this DataSnapshot.
*/
readonly ref: DatabaseReference,
readonly _index: Index
) {}
/**
* Gets the priority value of the data in this `DataSnapshot`.
*
* Applications need not use priority but can order collections by
* ordinary properties (see
* {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}
* ).
*/
get priority(): string | number | null {
// typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)
return this._node.getPriority().val() as string | number | null;
}
/**
* The key (last part of the path) of the location of this `DataSnapshot`.
*
* The last token in a Database location is considered its key. For example,
* "ada" is the key for the /users/ada/ node. Accessing the key on any
* `DataSnapshot` will return the key for the location that generated it.
* However, accessing the key on the root URL of a Database will return
* `null`.
*/
get key(): string | null {
return this.ref.key;
}
/** Returns the number of child properties of this `DataSnapshot`. */
get size(): number {
return this._node.numChildren();
}
/**
* Gets another `DataSnapshot` for the location at the specified relative path.
*
* Passing a relative path to the `child()` method of a DataSnapshot returns
* another `DataSnapshot` for the location at the specified relative path. The
* relative path can either be a simple child name (for example, "ada") or a
* deeper, slash-separated path (for example, "ada/name/first"). If the child
* location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`
* whose value is `null`) is returned.
*
* @param path - A relative path to the location of child data.
*/
child(path: string): DataSnapshot {
const childPath = new Path(path);
const childRef = child(this.ref, path);
return new DataSnapshot(
this._node.getChild(childPath),
childRef,
PRIORITY_INDEX
);
}
/**
* Returns true if this `DataSnapshot` contains any data. It is slightly more
* efficient than using `snapshot.val() !== null`.
*/
exists(): boolean {
return !this._node.isEmpty();
}
/**
* Exports the entire contents of the DataSnapshot as a JavaScript object.
*
* The `exportVal()` method is similar to `val()`, except priority information
* is included (if available), making it suitable for backing up your data.
*
* @returns The DataSnapshot's contents as a JavaScript value (Object,
* Array, string, number, boolean, or `null`).
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
exportVal(): any {
return this._node.val(true);
}
/**
* Enumerates the top-level children in the `IteratedDataSnapshot`.
*
* Because of the way JavaScript objects work, the ordering of data in the
* JavaScript object returned by `val()` is not guaranteed to match the
* ordering on the server nor the ordering of `onChildAdded()` events. That is
* where `forEach()` comes in handy. It guarantees the children of a
* `DataSnapshot` will be iterated in their query order.
*
* If no explicit `orderBy*()` method is used, results are returned
* ordered by key (unless priorities are used, in which case, results are
* returned by priority).
*
* @param action - A function that will be called for each child DataSnapshot.
* The callback can return true to cancel further enumeration.
* @returns true if enumeration was canceled due to your callback returning
* true.
*/
forEach(action: (child: IteratedDataSnapshot) => boolean | void): boolean {
if (this._node.isLeafNode()) {
return false;
}
const childrenNode = this._node as ChildrenNode;
// Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...
return !!childrenNode.forEachChild(this._index, (key, node) => {
return action(
new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX)
);
});
}
/**
* Returns true if the specified child path has (non-null) data.
*
* @param path - A relative path to the location of a potential child.
* @returns `true` if data exists at the specified child path; else
* `false`.
*/
hasChild(path: string): boolean {
const childPath = new Path(path);
return !this._node.getChild(childPath).isEmpty();
}
/**
* Returns whether or not the `DataSnapshot` has any non-`null` child
* properties.
*
* You can use `hasChildren()` to determine if a `DataSnapshot` has any
* children. If it does, you can enumerate them using `forEach()`. If it
* doesn't, then either this snapshot contains a primitive value (which can be
* retrieved with `val()`) or it is empty (in which case, `val()` will return
* `null`).
*
* @returns true if this snapshot has any children; else false.
*/
hasChildren(): boolean {
if (this._node.isLeafNode()) {
return false;
} else {
return !this._node.isEmpty();
}
}
/**
* Returns a JSON-serializable representation of this object.
*/
toJSON(): object | null {
return this.exportVal();
}
/**
* Extracts a JavaScript value from a `DataSnapshot`.
*
* Depending on the data in a `DataSnapshot`, the `val()` method may return a
* scalar type (string, number, or boolean), an array, or an object. It may
* also return null, indicating that the `DataSnapshot` is empty (contains no
* data).
*
* @returns The DataSnapshot's contents as a JavaScript value (Object,
* Array, string, number, boolean, or `null`).
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
val(): any {
return this._node.val();
}
}
/**
* Represents a child snapshot of a `Reference` that is being iterated over. The key will never be undefined.
*/
export interface IteratedDataSnapshot extends DataSnapshot {
key: string; // key of the location of this snapshot.
}
/**
*
* Returns a `Reference` representing the location in the Database
* corresponding to the provided path. If no path is provided, the `Reference`
* will point to the root of the Database.
*
* @param db - The database instance to obtain a reference for.
* @param path - Optional path representing the location the returned
* `Reference` will point. If not provided, the returned `Reference` will
* point to the root of the Database.
* @returns If a path is provided, a `Reference`
* pointing to the provided path. Otherwise, a `Reference` pointing to the
* root of the Database.
*/
export function ref(db: Database, path?: string): DatabaseReference {
db = getModularInstance(db);
db._checkNotDeleted('ref');
return path !== undefined ? child(db._root, path) : db._root;
}
/**
* Returns a `Reference` representing the location in the Database
* corresponding to the provided Firebase URL.
*
* An exception is thrown if the URL is not a valid Firebase Database URL or it
* has a different domain than the current `Database` instance.
*
* Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored
* and are not applied to the returned `Reference`.
*
* @param db - The database instance to obtain a reference for.
* @param url - The Firebase URL at which the returned `Reference` will
* point.
* @returns A `Reference` pointing to the provided
* Firebase URL.
*/
export function refFromURL(db: Database, url: string): DatabaseReference {
db = getModularInstance(db);
db._checkNotDeleted('refFromURL');
const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);
validateUrl('refFromURL', parsedURL);
const repoInfo = parsedURL.repoInfo;
if (
!db._repo.repoInfo_.isCustomHost() &&
repoInfo.host !== db._repo.repoInfo_.host
) {
fatal(
'refFromURL' +
': Host name does not match the current database: ' +
'(found ' +
repoInfo.host +
' but expected ' +
db._repo.repoInfo_.host +
')'
);
}
return ref(db, parsedURL.path.toString());
}
/**
* Gets a `Reference` for the location at the specified relative path.
*
* The relative path can either be a simple child name (for example, "ada") or
* a deeper slash-separated path (for example, "ada/name/first").
*
* @param parent - The parent location.
* @param path - A relative path from this location to the desired child
* location.
* @returns The specified child location.
*/
export function child(
parent: DatabaseReference,
path: string
): DatabaseReference {
parent = getModularInstance(parent);
if (pathGetFront(parent._path) === null) {
validateRootPathString('child', 'path', path, false);
} else {
validatePathString('child', 'path', path, false);
}
return new ReferenceImpl(parent._repo, pathChild(parent._path, path));
}
/**
* Returns an `OnDisconnect` object - see
* {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
* for more information on how to use it.
*
* @param ref - The reference to add OnDisconnect triggers for.
*/
export function onDisconnect(ref: DatabaseReference): OnDisconnect {
ref = getModularInstance(ref) as ReferenceImpl;
return new OnDisconnect(ref._repo, ref._path);
}
export interface ThenableReferenceImpl
extends ReferenceImpl,
Pick<Promise<ReferenceImpl>, 'then' | 'catch'> {
key: string;
parent: ReferenceImpl;
}
/**
* Generates a new child location using a unique key and returns its
* `Reference`.
*
* This is the most common pattern for adding data to a collection of items.
*
* If you provide a value to `push()`, the value is written to the
* generated location. If you don't pass a value, nothing is written to the
* database and the child remains empty (but you can use the `Reference`
* elsewhere).
*
* The unique keys generated by `push()` are ordered by the current time, so the
* resulting list of items is chronologically sorted. The keys are also
* designed to be unguessable (they contain 72 random bits of entropy).
*
* See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.
* See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.
*
* @param parent - The parent location.
* @param value - Optional value to be written at the generated location.
* @returns Combined `Promise` and `Reference`; resolves when write is complete,
* but can be used immediately as the `Reference` to the child location.
*/
export function push(
parent: DatabaseReference,
value?: unknown
): ThenableReference {
parent = getModularInstance(parent);
validateWritablePath('push', parent._path);
validateFirebaseDataArg('push', value, parent._path, true);
const now = repoServerTime(parent._repo);
const name = nextPushId(now);
// push() returns a ThennableReference whose promise is fulfilled with a
// regular Reference. We use child() to create handles to two different
// references. The first is turned into a ThennableReference below by adding
// then() and catch() methods and is used as the return value of push(). The
// second remains a regular Reference and is used as the fulfilled value of
// the first ThennableReference.
const thenablePushRef: Partial<ThenableReferenceImpl> = child(
parent,
name
) as ReferenceImpl;
const pushRef = child(parent, name) as ReferenceImpl;
let promise: Promise<ReferenceImpl>;
if (value != null) {
promise = set(pushRef, value).then(() => pushRef);
} else {
promise = Promise.resolve(pushRef);
}
thenablePushRef.then = promise.then.bind(promise);
thenablePushRef.catch = promise.then.bind(promise, undefined);
return thenablePushRef as ThenableReferenceImpl;
}
/**
* Removes the data at this Database location.
*
* Any data at child locations will also be deleted.
*
* The effect of the remove will be visible immediately and the corresponding
* event 'value' will be triggered. Synchronization of the remove to the
* Firebase servers will also be started, and the returned Promise will resolve
* when complete. If provided, the onComplete callback will be called
* asynchronously after synchronization has finished.
*
* @param ref - The location to remove.
* @returns Resolves when remove on server is complete.
*/
export function remove(ref: DatabaseReference): Promise<void> {
validateWritablePath('remove', ref._path);
return set(ref, null);
}
/**
* Writes data to this Database location.
*
* This will overwrite any data at this location and all child locations.
*
* The effect of the write will be visible immediately, and the corresponding
* events ("value", "child_added", etc.) will be triggered. Synchronization of
* the data to the Firebase servers will also be started, and the returned
* Promise will resolve when complete. If provided, the `onComplete` callback
* will be called asynchronously after synchronization has finished.
*
* Passing `null` for the new value is equivalent to calling `remove()`; namely,
* all data at this location and all child locations will be deleted.
*
* `set()` will remove any priority stored at this location, so if priority is
* meant to be preserved, you need to use `setWithPriority()` instead.
*
* Note that modifying data with `set()` will cancel any pending transactions
* at that location, so extreme care should be taken if mixing `set()` and
* `transaction()` to modify the same data.
*
* A single `set()` will generate a single "value" event at the location where
* the `set()` was performed.
*
* @param ref - The location to write to.
* @param value - The value to be written (string, number, boolean, object,
* array, or null).
* @returns Resolves when write to server is complete.
*/
export function set(ref: DatabaseReference, value: unknown): Promise<void> {
ref = getModularInstance(ref);
validateWritablePath('set', ref._path);
validateFirebaseDataArg('set', value, ref._path, false);
const deferred = new Deferred<void>();
repoSetWithPriority(
ref._repo,
ref._path,
value,
/*priority=*/ null,
deferred.wrapCallback(() => {})
);
return deferred.promise;
}
/**
* Sets a priority for the data at this Database location.
*
* Applications need not use priority but can order collections by
* ordinary properties (see
* {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
* ).
*
* @param ref - The location to write to.
* @param priority - The priority to be written (string, number, or null).
* @returns Resolves when write to server is complete.
*/
export function setPriority(
ref: DatabaseReference,
priority: string | number | null
): Promise<void> {
ref = getModularInstance(ref);
validateWritablePath('setPriority', ref._path);
validatePriority('setPriority', priority, false);
const deferred = new Deferred<void>();
repoSetWithPriority(
ref._repo,
pathChild(ref._path, '.priority'),
priority,
null,
deferred.wrapCallback(() => {})
);
return deferred.promise;
}
/**
* Writes data the Database location. Like `set()` but also specifies the
* priority for that data.
*
* Applications need not use priority but can order collections by
* ordinary properties (see
* {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
* ).
*
* @param ref - The location to write to.
* @param value - The value to be written (string, number, boolean, object,
* array, or null).
* @param priority - The priority to be written (string, number, or null).
* @returns Resolves when write to server is complete.
*/
export function setWithPriority(
ref: DatabaseReference,
value: unknown,
priority: string | number | null
): Promise<void> {
validateWritablePath('setWithPriority', ref._path);
validateFirebaseDataArg('setWithPriority', value, ref._path, false);
validatePriority('setWithPriority', priority, false);
if (ref.key === '.length' || ref.key === '.keys') {
throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';
}
const deferred = new Deferred<void>();
repoSetWithPriority(
ref._repo,
ref._path,
value,
priority,
deferred.wrapCallback(() => {})
);
return deferred.promise;
}
/**
* Writes multiple values to the Database at once.
*
* The `values` argument contains multiple property-value pairs that will be
* written to the Database together. Each child property can either be a simple
* property (for example, "name") or a relative path (for example,
* "name/first") from the current location to the data to update.
*
* As opposed to the `set()` method, `update()` can be use to selectively update
* only the referenced properties at the current location (instead of replacing
* all the child properties at the current location).
*
* The effect of the write will be visible immediately, and the corresponding
* events ('value', 'child_added', etc.) will be triggered. Synchronization of
* the data to the Firebase servers will also be started, and the returned
* Promise will resolve when complete. If provided, the `onComplete` callback
* will be called asynchronously after synchronization has finished.
*
* A single `update()` will generate a single "value" event at the location
* where the `update()` was performed, regardless of how many children were
* modified.
*
* Note that modifying data with `update()` will cancel any pending
* transactions at that location, so extreme care should be taken if mixing
* `update()` and `transaction()` to modify the same data.
*
* Passing `null` to `update()` will remove the data at this location.
*
* See
* {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.
*
* @param ref - The location to write to.
* @param values - Object containing multiple values.
* @returns Resolves when update on server is complete.
*/
export function update(ref: DatabaseReference, values: object): Promise<void> {
validateFirebaseMergeDataArg('update', values, ref._path, false);
const deferred = new Deferred<void>();
repoUpdate(
ref._repo,
ref._path,
values as Record<string, unknown>,
deferred.wrapCallback(() => {})
);
return deferred.promise;
}
/**
* Gets the most up-to-date result for this query.
*
* @param query - The query to run.
* @returns A `Promise` which resolves to the resulting DataSnapshot if a value is
* available, or rejects if the client is unable to return a value (e.g., if the
* server is unreachable and there is nothing cached).
*/
export function get(query: Query): Promise<DataSnapshot> {
query = getModularInstance(query) as QueryImpl;
const callbackContext = new CallbackContext(() => {});
const container = new ValueEventRegistration(callbackContext);
return repoGetValue(query._repo, query, container).then(node => {
return new DataSnapshot(
node,
new ReferenceImpl(query._repo, query._path),
query._queryParams.getIndex()
);
});
}
/**
* Represents registration for 'value' events.
*/
export class ValueEventRegistration implements EventRegistration {
constructor(private callbackContext: CallbackContext) {}
respondsTo(eventType: string): boolean {
return eventType === 'value';
}
createEvent(change: Change, query: QueryContext): DataEvent {
const index = query._queryParams.getIndex();
return new DataEvent(
'value',
this,
new DataSnapshot(
change.snapshotNode,
new ReferenceImpl(query._repo, query._path),
index
)
);
}
getEventRunner(eventData: CancelEvent | DataEvent): () => void {
if (eventData.getEventType() === 'cancel') {
return () =>
this.callbackContext.onCancel((eventData as CancelEvent).error);
} else {
return () =>
this.callbackContext.onValue((eventData as DataEvent).snapshot, null);
}
}
createCancelEvent(error: Error, path: Path): CancelEvent | null {
if (this.callbackContext.hasCancelCallback) {
return new CancelEvent(this, error, path);
} else {
return null;
}
}
matches(other: EventRegistration): boolean {
if (!(other instanceof ValueEventRegistration)) {
return false;
} else if (!other.callbackContext || !this.callbackContext) {
// If no callback specified, we consider it to match any callback.
return true;
} else {
return other.callbackContext.matches(this.callbackContext);
}
}
hasAnyCallback(): boolean {
return this.callbackContext !== null;
}
}
/**
* Represents the registration of a child_x event.
*/
export class ChildEventRegistration implements EventRegistration {
constructor(
private eventType: string,
private callbackContext: CallbackContext | null
) {}
respondsTo(eventType: string): boolean {
let eventToCheck =
eventType === 'children_added' ? 'child_added' : eventType;
eventToCheck =
eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;
return this.eventType === eventToCheck;
}
createCancelEvent(error: Error, path: Path): CancelEvent | null {
if (this.callbackContext.hasCancelCallback) {
return new CancelEvent(this, error, path);
} else {
return null;
}
}
createEvent(change: Change, query: QueryContext): DataEvent {
assert(change.childName != null, 'Child events should have a childName.');
const childRef = child(
new ReferenceImpl(query._repo, query._path),
change.childName
);
const index = query._queryParams.getIndex();
return new DataEvent(
change.type as EventType,
this,
new DataSnapshot(change.snapshotNode, childRef, index),
change.prevName
);
}
getEventRunner(eventData: CancelEvent | DataEvent): () => void {
if (eventData.getEventType() === 'cancel') {
return () =>
this.callbackContext.onCancel((eventData as CancelEvent).error);
} else {
return () =>
this.callbackContext.onValue(
(eventData as DataEvent).snapshot,
(eventData as DataEvent).prevName
);
}
}
matches(other: EventRegistration): boolean {
if (other instanceof ChildEventRegistration) {
return (
this.eventType === other.eventType &&
(!this.callbackContext ||
!other.callbackContext ||
this.callbackContext.matches(other.callbackContext))
);
}
return false;
}
hasAnyCallback(): boolean {
return !!this.callbackContext;
}
}
function addEventListener(
query: Query,
eventType: EventType,
callback: UserCallback,
cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,
options?: ListenOptions
) {
let cancelCallback: ((error: Error) => unknown) | undefined;
if (typeof cancelCallbackOrListenOptions === 'object') {
cancelCallback = undefined;
options = cancelCallbackOrListenOptions;
}
if (typeof cancelCallbackOrListenOptions === 'function') {
cancelCallback = cancelCallbackOrListenOptions;
}
if (options && options.onlyOnce) {
const userCallback = callback;
const onceCallback: UserCallback = (dataSnapshot, previousChildName) => {
repoRemoveEventCallbackForQuery(query._repo, query, container);
userCallback(dataSnapshot, previousChildName);
};
onceCallback.userCallback = callback.userCallback;
onceCallback.context = callback.context;
callback = onceCallback;
}
const callbackContext = new CallbackContext(
callback,
cancelCallback || undefined
);
const container =
eventType === 'value'
? new ValueEventRegistration(callbackContext)
: new ChildEventRegistration(eventType, callbackContext);
repoAddEventCallbackForQuery(query._repo, query, container);
return () => repoRemoveEventCallbackForQuery(query._repo, query, container);
}
/**
* Listens for data changes at a particular location.
*