/
reference.ts
2365 lines (2178 loc) · 70.9 KB
/
reference.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
/*!
* Copyright 2017 Google Inc. All Rights Reserved.
*
* 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.
*/
const deepEqual = require('deep-equal');
import * as bun from 'bun';
import * as through2 from 'through2';
import * as proto from '../protos/firestore_v1_proto_api';
import {
DocumentSnapshot,
DocumentSnapshotBuilder,
QueryDocumentSnapshot,
} from './document';
import {DocumentChange} from './document-change';
import {Firestore} from './index';
import {logger} from './logger';
import {compare} from './order';
import {
FieldPath,
QualifiedResourcePath,
ResourcePath,
validateFieldPath,
validateResourcePath,
} from './path';
import {Serializable, Serializer, validateUserInput} from './serializer';
import {Timestamp} from './timestamp';
import {
DocumentData,
OrderByDirection,
Precondition,
SetOptions,
UpdateData,
WhereFilterOp,
} from './types';
import {autoId, requestTag} from './util';
import {
invalidArgumentMessage,
validateEnumValue,
validateFunction,
validateInteger,
validateMinNumberOfArguments,
} from './validate';
import {defaultConverter, DocumentWatch, QueryWatch} from './watch';
import {validateDocumentData, WriteBatch, WriteResult} from './write-batch';
import api = proto.google.firestore.v1;
import {FirestoreDataConverter} from '@google-cloud/firestore';
/**
* The direction of a `Query.orderBy()` clause is specified as 'desc' or 'asc'
* (descending or ascending).
*
* @private
*/
const directionOperators: {[k: string]: api.StructuredQuery.Direction} = {
asc: 'ASCENDING',
desc: 'DESCENDING',
};
/**
* Filter conditions in a `Query.where()` clause are specified using the
* strings '<', '<=', '==', '>=', '>', 'array-contains', 'in', and
* 'array-contains-any'.
*
* @private
*/
const comparisonOperators: {
[k: string]: api.StructuredQuery.FieldFilter.Operator;
} = {
'<': 'LESS_THAN',
'<=': 'LESS_THAN_OR_EQUAL',
'==': 'EQUAL',
'>': 'GREATER_THAN',
'>=': 'GREATER_THAN_OR_EQUAL',
'array-contains': 'ARRAY_CONTAINS',
in: 'IN',
'array-contains-any': 'ARRAY_CONTAINS_ANY',
};
/**
* onSnapshot() callback that receives a QuerySnapshot.
*
* @callback querySnapshotCallback
* @param {QuerySnapshot} snapshot A query snapshot.
*/
/**
* onSnapshot() callback that receives a DocumentSnapshot.
*
* @callback documentSnapshotCallback
* @param {DocumentSnapshot} snapshot A document snapshot.
*/
/**
* onSnapshot() callback that receives an error.
*
* @callback errorCallback
* @param {Error} err An error from a listen.
*/
/**
* A DocumentReference refers to a document location in a Firestore database
* and can be used to write, read, or listen to the location. The document at
* the referenced location may or may not exist. A DocumentReference can
* also be used to create a
* [CollectionReference]{@link CollectionReference} to a
* subcollection.
*
* @class
*/
export class DocumentReference<T = DocumentData> implements Serializable {
readonly _converter: FirestoreDataConverter<T>;
/**
* @hideconstructor
*
* @param _firestore The Firestore Database client.
* @param _path The Path of this reference.
*/
constructor(
private readonly _firestore: Firestore,
readonly _path: ResourcePath,
converter?: FirestoreDataConverter<T>
) {
this._converter =
converter || (defaultConverter as FirestoreDataConverter<T>);
}
/**
* The string representation of the DocumentReference's location.
* @private
* @type {string}
* @name DocumentReference#formattedName
*/
get formattedName(): string {
const projectId = this.firestore.projectId;
return this._path.toQualifiedResourcePath(projectId).formattedName;
}
/**
* The [Firestore]{@link Firestore} instance for the Firestore
* database (useful for performing transactions, etc.).
*
* @type {Firestore}
* @name DocumentReference#firestore
* @readonly
*
* @example
* let collectionRef = firestore.collection('col');
*
* collectionRef.add({foo: 'bar'}).then(documentReference => {
* let firestore = documentReference.firestore;
* console.log(`Root location for document is ${firestore.formattedName}`);
* });
*/
get firestore(): Firestore {
return this._firestore;
}
/**
* A string representing the path of the referenced document (relative
* to the root of the database).
*
* @type {string}
* @name DocumentReference#path
* @readonly
*
* @example
* let collectionRef = firestore.collection('col');
*
* collectionRef.add({foo: 'bar'}).then(documentReference => {
* console.log(`Added document at '${documentReference.path}'`);
* });
*/
get path(): string {
return this._path.relativeName;
}
/**
* The last path element of the referenced document.
*
* @type {string}
* @name DocumentReference#id
* @readonly
*
* @example
* let collectionRef = firestore.collection('col');
*
* collectionRef.add({foo: 'bar'}).then(documentReference => {
* console.log(`Added document with name '${documentReference.id}'`);
* });
*/
get id(): string {
return this._path.id!;
}
/**
* A reference to the collection to which this DocumentReference belongs.
*
* @name DocumentReference#parent
* @type {CollectionReference}
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
* let collectionRef = documentRef.parent;
*
* collectionRef.where('foo', '==', 'bar').get().then(results => {
* console.log(`Found ${results.size} matches in parent collection`);
* }):
*/
get parent(): CollectionReference<T> {
return new CollectionReference(
this._firestore,
this._path.parent()!,
this._converter
);
}
/**
* Reads the document referred to by this DocumentReference.
*
* @returns {Promise.<DocumentSnapshot>} A Promise resolved with a
* DocumentSnapshot for the retrieved document on success. For missing
* documents, DocumentSnapshot.exists will be false. If the get() fails for
* other reasons, the Promise will be rejected.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(documentSnapshot => {
* if (documentSnapshot.exists) {
* console.log('Document retrieved successfully.');
* }
* });
*/
get(): Promise<DocumentSnapshot<T>> {
return this._firestore.getAll(this).then(([result]) => result);
}
/**
* Gets a [CollectionReference]{@link CollectionReference} instance
* that refers to the collection at the specified path.
*
* @param {string} collectionPath A slash-separated path to a collection.
* @returns {CollectionReference} A reference to the new
* subcollection.
*
* @example
* let documentRef = firestore.doc('col/doc');
* let subcollection = documentRef.collection('subcollection');
* console.log(`Path to subcollection: ${subcollection.path}`);
*/
collection(collectionPath: string): CollectionReference<DocumentData> {
validateResourcePath('collectionPath', collectionPath);
const path = this._path.append(collectionPath);
if (!path.isCollection) {
throw new Error(
`Value for argument "collectionPath" must point to a collection, but was "${collectionPath}". Your path does not contain an odd number of components.`
);
}
return new CollectionReference(this._firestore, path);
}
/**
* Fetches the subcollections that are direct children of this document.
*
* @returns {Promise.<Array.<CollectionReference>>} A Promise that resolves
* with an array of CollectionReferences.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.listCollections().then(collections => {
* for (let collection of collections) {
* console.log(`Found subcollection with id: ${collection.id}`);
* }
* });
*/
listCollections(): Promise<Array<CollectionReference<DocumentData>>> {
const tag = requestTag();
return this.firestore.initializeIfNeeded(tag).then(() => {
const request = {parent: this.formattedName};
return this._firestore
.request<string[]>(
'listCollectionIds',
request,
tag,
/* allowRetries= */ true
)
.then(collectionIds => {
const collections: Array<CollectionReference<DocumentData>> = [];
// We can just sort this list using the default comparator since it
// will only contain collection ids.
collectionIds.sort();
for (const collectionId of collectionIds) {
collections.push(this.collection(collectionId));
}
return collections;
});
});
}
/**
* Create a document with the provided object values. This will fail the write
* if a document exists at its location.
*
* @param {DocumentData} data An object that contains the fields and data to
* serialize as the document.
* @returns {Promise.<WriteResult>} A Promise that resolves with the
* write time of this create.
*
* @example
* let documentRef = firestore.collection('col').doc();
*
* documentRef.create({foo: 'bar'}).then((res) => {
* console.log(`Document created at ${res.updateTime}`);
* }).catch((err) => {
* console.log(`Failed to create document: ${err}`);
* });
*/
create(data: T): Promise<WriteResult> {
const writeBatch = new WriteBatch(this._firestore);
return writeBatch
.create(this, data)
.commit()
.then(([writeResult]) => writeResult);
}
/**
* Deletes the document referred to by this `DocumentReference`.
*
* A delete for a non-existing document is treated as a success (unless
* lastUptimeTime is provided).
*
* @param {Precondition=} precondition A precondition to enforce for this
* delete.
* @param {Timestamp=} precondition.lastUpdateTime If set, enforces that the
* document was last updated at lastUpdateTime. Fails the delete if the
* document was last updated at a different time.
* @returns {Promise.<WriteResult>} A Promise that resolves with the
* delete time.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.delete().then(() => {
* console.log('Document successfully deleted.');
* });
*/
delete(precondition?: Precondition): Promise<WriteResult> {
const writeBatch = new WriteBatch(this._firestore);
return writeBatch
.delete(this, precondition)
.commit()
.then(([writeResult]) => writeResult);
}
/**
* Writes to the document referred to by this DocumentReference. If the
* document does not yet exist, it will be created. If you pass
* [SetOptions]{@link SetOptions}, the provided data can be merged into an
* existing document.
*
* @param {T} data A map of the fields and values for the document.
* @param {SetOptions=} options An object to configure the set behavior.
* @param {boolean=} options.merge If true, set() merges the values specified
* in its data argument. Fields omitted from this set() call remain untouched.
* @param {Array.<string|FieldPath>=} options.mergeFields If provided,
* set() only replaces the specified field paths. Any field path that is not
* specified is ignored and remains untouched.
* @returns {Promise.<WriteResult>} A Promise that resolves with the
* write time of this set.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.set({foo: 'bar'}).then(res => {
* console.log(`Document written at ${res.updateTime}`);
* });
*/
set(data: T, options?: SetOptions): Promise<WriteResult> {
const writeBatch = new WriteBatch(this._firestore);
return writeBatch
.set(this, data, options)
.commit()
.then(([writeResult]) => writeResult);
}
/**
* Updates fields in the document referred to by this DocumentReference.
* If the document doesn't yet exist, the update fails and the returned
* Promise will be rejected.
*
* The update() method accepts either an object with field paths encoded as
* keys and field values encoded as values, or a variable number of arguments
* that alternate between field paths and field values.
*
* A Precondition restricting this update can be specified as the last
* argument.
*
* @param {UpdateData|string|FieldPath} dataOrField An object containing the
* fields and values with which to update the document or the path of the
* first field to update.
* @param {
* ...(*|string|FieldPath|Precondition)} preconditionOrValues An alternating
* list of field paths and values to update or a Precondition to restrict
* this update.
* @returns {Promise.<WriteResult>} A Promise that resolves once the
* data has been successfully written to the backend.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.update({foo: 'bar'}).then(res => {
* console.log(`Document updated at ${res.updateTime}`);
* });
*/
update(
dataOrField: UpdateData | string | FieldPath,
...preconditionOrValues: Array<unknown | string | FieldPath | Precondition>
): Promise<WriteResult> {
validateMinNumberOfArguments('DocumentReference.update', arguments, 1);
const writeBatch = new WriteBatch(this._firestore);
return writeBatch.update
.apply(writeBatch, [
this as DocumentReference<unknown>,
dataOrField,
...preconditionOrValues,
])
.commit()
.then(([writeResult]) => writeResult);
}
/**
* Attaches a listener for DocumentSnapshot events.
*
* @param {documentSnapshotCallback} onNext A callback to be called every
* time a new `DocumentSnapshot` is available.
* @param {errorCallback=} onError A callback to be called if the listen fails
* or is cancelled. No further callbacks will occur. If unset, errors will be
* logged to the console.
*
* @returns {function()} An unsubscribe function that can be called to cancel
* the snapshot listener.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* let unsubscribe = documentRef.onSnapshot(documentSnapshot => {
* if (documentSnapshot.exists) {
* console.log(documentSnapshot.data());
* }
* }, err => {
* console.log(`Encountered error: ${err}`);
* });
*
* // Remove this listener.
* unsubscribe();
*/
onSnapshot(
onNext: (snapshot: DocumentSnapshot<T>) => void,
onError?: (error: Error) => void
): () => void {
validateFunction('onNext', onNext);
validateFunction('onError', onError, {optional: true});
const watch = new DocumentWatch(this.firestore, this, this._converter);
return watch.onSnapshot((readTime, size, docs) => {
for (const document of docs()) {
if (document.ref.path === this.path) {
onNext(document);
return;
}
}
// The document is missing.
const document = new DocumentSnapshotBuilder<T>();
document.ref = new DocumentReference(
this._firestore,
this._path,
this._converter
);
document.readTime = readTime;
onNext(document.build());
}, onError || console.error);
}
/**
* Returns true if this `DocumentReference` is equal to the provided value.
*
* @param {*} other The value to compare against.
* @return {boolean} true if this `DocumentReference` is equal to the provided
* value.
*/
isEqual(other: DocumentReference<T>): boolean {
return (
this === other ||
(other instanceof DocumentReference &&
this._firestore === other._firestore &&
this._path.isEqual(other._path))
);
}
/**
* Converts this DocumentReference to the Firestore Proto representation.
*
* @private
*/
toProto(): api.IValue {
return {referenceValue: this.formattedName};
}
/**
* Applies a custom data converter to this DocumentReference, allowing you
* to use your own custom model objects with Firestore. When you call
* set(), get(), etc. on the returned DocumentReference instance, the
* provided converter will convert between Firestore data and your custom
* type U.
*
* @param converter Converts objects to and from Firestore.
* @return A DocumentReference<U> that uses the provided converter.
*/
withConverter<U>(converter: FirestoreDataConverter<U>): DocumentReference<U> {
return new DocumentReference<U>(this.firestore, this._path, converter);
}
}
/**
* A Query order-by field.
*
* @private
* @class
*/
class FieldOrder {
/**
* @param field The name of a document field (member) on which to order query
* results.
* @param direction One of 'ASCENDING' (default) or 'DESCENDING' to
* set the ordering direction to ascending or descending, respectively.
*/
constructor(
readonly field: FieldPath,
readonly direction: api.StructuredQuery.Direction = 'ASCENDING'
) {}
/**
* Generates the proto representation for this field order.
* @private
*/
toProto(): api.StructuredQuery.IOrder {
return {
field: {
fieldPath: this.field.formattedName,
},
direction: this.direction,
};
}
}
/**
* A field constraint for a Query where clause.
*
* @private
* @class
*/
class FieldFilter {
/**
* @param serializer The Firestore serializer
* @param field The path of the property value to compare.
* @param op A comparison operation.
* @param value The value to which to compare the field for inclusion in a
* query.
*/
constructor(
private readonly serializer: Serializer,
readonly field: FieldPath,
private readonly op: api.StructuredQuery.FieldFilter.Operator,
private readonly value: unknown
) {}
/**
* Returns whether this FieldFilter uses an equals comparison.
*
* @private
*/
isInequalityFilter(): boolean {
switch (this.op) {
case 'GREATER_THAN':
case 'GREATER_THAN_OR_EQUAL':
case 'LESS_THAN':
case 'LESS_THAN_OR_EQUAL':
return true;
default:
return false;
}
}
/**
* Generates the proto representation for this field filter.
*
* @private
*/
toProto(): api.StructuredQuery.IFilter {
if (typeof this.value === 'number' && isNaN(this.value)) {
return {
unaryFilter: {
field: {
fieldPath: this.field.formattedName,
},
op: 'IS_NAN',
},
};
}
if (this.value === null) {
return {
unaryFilter: {
field: {
fieldPath: this.field.formattedName,
},
op: 'IS_NULL',
},
};
}
return {
fieldFilter: {
field: {
fieldPath: this.field.formattedName,
},
op: this.op,
value: this.serializer.encodeValue(this.value),
},
};
}
}
/**
* A QuerySnapshot contains zero or more
* [QueryDocumentSnapshot]{@link QueryDocumentSnapshot} objects
* representing the results of a query. The documents can be accessed as an
* array via the [documents]{@link QuerySnapshot#documents} property
* or enumerated using the [forEach]{@link QuerySnapshot#forEach}
* method. The number of documents can be determined via the
* [empty]{@link QuerySnapshot#empty} and
* [size]{@link QuerySnapshot#size} properties.
*
* @class QuerySnapshot
*/
export class QuerySnapshot<T = DocumentData> {
private _materializedDocs: Array<QueryDocumentSnapshot<T>> | null = null;
private _materializedChanges: Array<DocumentChange<T>> | null = null;
private _docs: (() => Array<QueryDocumentSnapshot<T>>) | null = null;
private _changes: (() => Array<DocumentChange<T>>) | null = null;
private readonly _converter: FirestoreDataConverter<T>;
/**
* @hideconstructor
*
* @param _query The originating query.
* @param _readTime The time when this query snapshot was obtained.
* @param _size The number of documents in the result set.
* @param docs A callback returning a sorted array of documents matching
* this query
* @param changes A callback returning a sorted array of document change
* events for this snapshot.
* @param _converter The converter used to converter between Firestore and
* user objects.
*/
constructor(
private readonly _query: Query<T>,
private readonly _readTime: Timestamp,
private readonly _size: number,
docs: () => Array<QueryDocumentSnapshot<T>>,
changes: () => Array<DocumentChange<T>>,
converter?: FirestoreDataConverter<T>
) {
this._docs = docs;
this._changes = changes;
this._converter =
converter || (defaultConverter as FirestoreDataConverter<T>);
}
/**
* The query on which you called get() or onSnapshot() in order to get this
* QuerySnapshot.
*
* @type {Query}
* @name QuerySnapshot#query
* @readonly
*
* @example
* let query = firestore.collection('col').where('foo', '==', 'bar');
*
* query.limit(10).get().then(querySnapshot => {
* console.log(`Returned first batch of results`);
* let query = querySnapshot.query;
* return query.offset(10).get();
* }).then(() => {
* console.log(`Returned second batch of results`);
* });
*/
get query(): Query<T> {
return this._query;
}
/**
* An array of all the documents in this QuerySnapshot.
*
* @type {Array.<QueryDocumentSnapshot>}
* @name QuerySnapshot#docs
* @readonly
*
* @example
* let query = firestore.collection('col').where('foo', '==', 'bar');
*
* query.get().then(querySnapshot => {
* let docs = querySnapshot.docs;
* for (let doc of docs) {
* console.log(`Document found at path: ${doc.ref.path}`);
* }
* });
*/
get docs(): Array<QueryDocumentSnapshot<T>> {
if (this._materializedDocs) {
return this._materializedDocs!;
}
this._materializedDocs = this._docs!();
this._docs = null;
return this._materializedDocs!;
}
/**
* True if there are no documents in the QuerySnapshot.
*
* @type {boolean}
* @name QuerySnapshot#empty
* @readonly
*
* @example
* let query = firestore.collection('col').where('foo', '==', 'bar');
*
* query.get().then(querySnapshot => {
* if (querySnapshot.empty) {
* console.log('No documents found.');
* }
* });
*/
get empty(): boolean {
return this._size === 0;
}
/**
* The number of documents in the QuerySnapshot.
*
* @type {number}
* @name QuerySnapshot#size
* @readonly
*
* @example
* let query = firestore.collection('col').where('foo', '==', 'bar');
*
* query.get().then(querySnapshot => {
* console.log(`Found ${querySnapshot.size} documents.`);
* });
*/
get size(): number {
return this._size;
}
/**
* The time this query snapshot was obtained.
*
* @type {Timestamp}
* @name QuerySnapshot#readTime
*
* @example
* let query = firestore.collection('col').where('foo', '==', 'bar');
*
* query.get().then((querySnapshot) => {
* let readTime = querySnapshot.readTime;
* console.log(`Query results returned at '${readTime.toDate()}'`);
* });
*/
get readTime(): Timestamp {
return this._readTime;
}
/**
* Returns an array of the documents changes since the last snapshot. If
* this is the first snapshot, all documents will be in the list as added
* changes.
*
* @return {Array.<DocumentChange>}
*
* @example
* let query = firestore.collection('col').where('foo', '==', 'bar');
*
* query.onSnapshot(querySnapshot => {
* let changes = querySnapshot.docChanges();
* for (let change of changes) {
* console.log(`A document was ${change.type}.`);
* }
* });
*/
docChanges(): Array<DocumentChange<T>> {
if (this._materializedChanges) {
return this._materializedChanges!;
}
this._materializedChanges = this._changes!();
this._changes = null;
return this._materializedChanges!;
}
/**
* Enumerates all of the documents in the QuerySnapshot. This is a convenience
* method for running the same callback on each {@link QueryDocumentSnapshot}
* that is returned.
*
* @param {function} callback A callback to be called with a
* [QueryDocumentSnapshot]{@link QueryDocumentSnapshot} for each document in
* the snapshot.
* @param {*=} thisArg The `this` binding for the callback..
*
* @example
* let query = firestore.collection('col').where('foo', '==', 'bar');
*
* query.get().then(querySnapshot => {
* querySnapshot.forEach(documentSnapshot => {
* console.log(`Document found at path: ${documentSnapshot.ref.path}`);
* });
* });
*/
forEach(
callback: (result: QueryDocumentSnapshot<T>) => void,
thisArg?: unknown
): void {
validateFunction('callback', callback);
for (const doc of this.docs) {
callback.call(thisArg, doc);
}
}
/**
* Returns true if the document data in this `QuerySnapshot` is equal to the
* provided value.
*
* @param {*} other The value to compare against.
* @return {boolean} true if this `QuerySnapshot` is equal to the provided
* value.
*/
isEqual(other: QuerySnapshot<T>): boolean {
// Since the read time is different on every query read, we explicitly
// ignore all metadata in this comparison.
if (this === other) {
return true;
}
if (!(other instanceof QuerySnapshot)) {
return false;
}
if (this._size !== other._size) {
return false;
}
if (!this._query.isEqual(other._query)) {
return false;
}
if (this._materializedDocs && !this._materializedChanges) {
// If we have only materialized the documents, we compare them first.
return (
isArrayEqual(this.docs, other.docs) &&
isArrayEqual(this.docChanges(), other.docChanges())
);
}
if (this._converter !== other._converter) {
return false;
}
// Otherwise, we compare the changes first as we expect there to be fewer.
return (
isArrayEqual(this.docChanges(), other.docChanges()) &&
isArrayEqual(this.docs, other.docs)
);
}
}
// TODO: As of v0.17.0, we're changing docChanges from an array into a method.
// Because this is a runtime breaking change and somewhat subtle (both Array and
// Function have a .length, etc.), we'll replace commonly-used properties
// (including Symbol.iterator) to throw a custom error message. By our v1.0
// release, we should remove this code.
function throwDocChangesMethodError() {
throw new Error(
'QuerySnapshot.docChanges has been changed from a property into a ' +
'method, so usages like "querySnapshot.docChanges" should become ' +
'"querySnapshot.docChanges()"'
);
}
const docChangesPropertiesToOverride = [
'length',
'forEach',
'map',
...(typeof Symbol !== 'undefined' ? [Symbol.iterator] : []),
];
docChangesPropertiesToOverride.forEach(property => {
Object.defineProperty(QuerySnapshot.prototype.docChanges, property, {
get: () => throwDocChangesMethodError(),
});
});
/** Internal representation of a query cursor before serialization. */
interface QueryCursor {
before?: boolean;
values: unknown[];
}
/**
* Internal class representing custom Query options.
*
* These options are immutable. Modified options can be created using `with()`.
* @private
*/
export class QueryOptions {
constructor(
readonly parentPath: ResourcePath,
readonly collectionId: string,
readonly allDescendants: boolean,
readonly fieldFilters: FieldFilter[],
readonly fieldOrders: FieldOrder[],
readonly startAt?: QueryCursor,
readonly endAt?: QueryCursor,
readonly limit?: number,
readonly offset?: number,
readonly projection?: api.StructuredQuery.IProjection
) {}
/**
* Returns query options for a collection group query.
* @private
*/
static forCollectionGroupQuery(collectionId: string): QueryOptions {
return new QueryOptions(
/*parentPath=*/ ResourcePath.EMPTY,
collectionId,
/*allDescendants=*/ true,
/*fieldFilters=*/ [],
/*fieldOrders=*/ []
);
}
/**
* Returns query options for a single-collection query.
* @private
*/
static forCollectionQuery(collectionRef: ResourcePath): QueryOptions {
return new QueryOptions(
collectionRef.parent()!,
collectionRef.id!,
/*allDescendants=*/ false,
/*fieldFilters=*/ [],
/*fieldOrders=*/ []
);
}
/**
* Returns the union of the current and the provided options.
* @private
*/
with(settings: Partial<QueryOptions>): QueryOptions {
return new QueryOptions(