/
document.ts
1075 lines (972 loc) · 28.5 KB
/
document.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 2019 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 assert from 'assert';
import {google} from '../protos/firestore_v1_proto_api';
import {FieldTransform} from './field-value';
import {FieldPath, validateFieldPath} from './path';
import {DocumentReference} from './reference';
import {isPlainObject, Serializer} from './serializer';
import {Timestamp} from './timestamp';
import {ApiMapValue, DocumentData, UpdateMap} from './types';
import {isEmpty, isObject} from './util';
import api = google.firestore.v1;
/**
* Returns a builder for DocumentSnapshot and QueryDocumentSnapshot instances.
* Invoke `.build()' to assemble the final snapshot.
*
* @private
*/
export class DocumentSnapshotBuilder<T = DocumentData> {
/** The reference to the document. */
ref: DocumentReference<T>;
/** The fields of the Firestore `Document` Protobuf backing this document. */
fieldsProto?: ApiMapValue;
/** The time when this document was read. */
readTime?: Timestamp;
/** The time when this document was created. */
createTime?: Timestamp;
/** The time when this document was last updated. */
updateTime?: Timestamp;
/**
* We include the DocumentReference in the constructor in order to allow the
* DocumentSnapshotBuilder to be typed with <T> when it is constructed.
*/
constructor(ref: DocumentReference<T>) {
this.ref = ref;
}
/**
* Builds the DocumentSnapshot.
*
* @private
* @returns Returns either a QueryDocumentSnapshot (if `fieldsProto` was
* provided) or a DocumentSnapshot.
*/
build(): QueryDocumentSnapshot<T> | DocumentSnapshot<T> {
assert(
(this.fieldsProto !== undefined) === (this.createTime !== undefined),
'Create time should be set iff document exists.'
);
assert(
(this.fieldsProto !== undefined) === (this.updateTime !== undefined),
'Update time should be set iff document exists.'
);
return this.fieldsProto
? new QueryDocumentSnapshot(
this.ref!,
this.fieldsProto!,
this.readTime!,
this.createTime!,
this.updateTime!
)
: new DocumentSnapshot(
this.ref!,
undefined,
this.readTime!,
undefined,
undefined
);
}
}
/**
* A DocumentSnapshot is an immutable representation for a document in a
* Firestore database. The data can be extracted with
* [data()]{@link DocumentSnapshot#data} or
* [get(fieldPath)]{@link DocumentSnapshot#get} to get a
* specific field.
*
* <p>For a DocumentSnapshot that points to a non-existing document, any data
* access will return 'undefined'. You can use the
* [exists]{@link DocumentSnapshot#exists} property to explicitly verify a
* document's existence.
*
* @class
*/
export class DocumentSnapshot<T = DocumentData> {
private _ref: DocumentReference<T>;
private _fieldsProto: ApiMapValue | undefined;
private _serializer: Serializer;
private _readTime: Timestamp | undefined;
private _createTime: Timestamp | undefined;
private _updateTime: Timestamp | undefined;
/**
* @hideconstructor
*
* @param ref The reference to the document.
* @param fieldsProto The fields of the Firestore `Document` Protobuf backing
* this document (or undefined if the document does not exist).
* @param readTime The time when this snapshot was read (or undefined if
* the document exists only locally).
* @param createTime The time when the document was created (or undefined if
* the document does not exist).
* @param updateTime The time when the document was last updated (or undefined
* if the document does not exist).
*/
constructor(
ref: DocumentReference<T>,
fieldsProto?: ApiMapValue,
readTime?: Timestamp,
createTime?: Timestamp,
updateTime?: Timestamp
) {
this._ref = ref;
this._fieldsProto = fieldsProto;
this._serializer = ref.firestore._serializer!;
this._readTime = readTime;
this._createTime = createTime;
this._updateTime = updateTime;
}
/**
* Creates a DocumentSnapshot from an object.
*
* @private
* @param ref The reference to the document.
* @param obj The object to store in the DocumentSnapshot.
* @return The created DocumentSnapshot.
*/
static fromObject<U>(
ref: DocumentReference<U>,
obj: DocumentData
): DocumentSnapshot<U> {
const serializer = ref.firestore._serializer!;
return new DocumentSnapshot(ref, serializer.encodeFields(obj));
}
/**
* Creates a DocumentSnapshot from an UpdateMap.
*
* This methods expands the top-level field paths in a JavaScript map and
* turns { foo.bar : foobar } into { foo { bar : foobar }}
*
* @private
* @param ref The reference to the document.
* @param data The field/value map to expand.
* @return The created DocumentSnapshot.
*/
static fromUpdateMap<U>(
ref: DocumentReference<U>,
data: UpdateMap
): DocumentSnapshot<U> {
const serializer = ref.firestore._serializer!;
/**
* Merges 'value' at the field path specified by the path array into
* 'target'.
*/
function merge(
target: ApiMapValue,
value: unknown,
path: string[],
pos: number
): ApiMapValue | null {
const key = path[pos];
const isLast = pos === path.length - 1;
if (target[key] === undefined) {
if (isLast) {
if (value instanceof FieldTransform) {
// If there is already data at this path, we need to retain it.
// Otherwise, we don't include it in the DocumentSnapshot.
return !isEmpty(target) ? target : null;
}
// The merge is done.
const leafNode = serializer.encodeValue(value);
if (leafNode) {
target[key] = leafNode;
}
return target;
} else {
// We need to expand the target object.
const childNode = {
mapValue: {
fields: {},
},
};
const nestedValue = merge(
childNode.mapValue.fields,
value,
path,
pos + 1
);
if (nestedValue) {
childNode.mapValue.fields = nestedValue;
target[key] = childNode;
return target;
} else {
return !isEmpty(target) ? target : null;
}
}
} else {
assert(!isLast, "Can't merge current value into a nested object");
target[key].mapValue!.fields = merge(
target[key].mapValue!.fields!,
value,
path,
pos + 1
);
return target;
}
}
const res: ApiMapValue = {};
for (const [key, value] of data) {
const path = key.toArray();
merge(res, value, path, 0);
}
return new DocumentSnapshot(ref, res);
}
/**
* True if the document exists.
*
* @type {boolean}
* @name DocumentSnapshot#exists
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then((documentSnapshot) => {
* if (documentSnapshot.exists) {
* console.log(`Data: ${JSON.stringify(documentSnapshot.data())}`);
* }
* });
*/
get exists(): boolean {
return this._fieldsProto !== undefined;
}
/**
* A [DocumentReference]{@link DocumentReference} for the document
* stored in this snapshot.
*
* @type {DocumentReference}
* @name DocumentSnapshot#ref
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then((documentSnapshot) => {
* if (documentSnapshot.exists) {
* console.log(`Found document at '${documentSnapshot.ref.path}'`);
* }
* });
*/
get ref(): DocumentReference<T> {
return this._ref;
}
/**
* The ID of the document for which this DocumentSnapshot contains data.
*
* @type {string}
* @name DocumentSnapshot#id
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then((documentSnapshot) => {
* if (documentSnapshot.exists) {
* console.log(`Document found with name '${documentSnapshot.id}'`);
* }
* });
*/
get id(): string {
return this._ref.id;
}
/**
* The time the document was created. Undefined for documents that don't
* exist.
*
* @type {Timestamp|undefined}
* @name DocumentSnapshot#createTime
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(documentSnapshot => {
* if (documentSnapshot.exists) {
* let createTime = documentSnapshot.createTime;
* console.log(`Document created at '${createTime.toDate()}'`);
* }
* });
*/
get createTime(): Timestamp | undefined {
return this._createTime;
}
/**
* The time the document was last updated (at the time the snapshot was
* generated). Undefined for documents that don't exist.
*
* @type {Timestamp|undefined}
* @name DocumentSnapshot#updateTime
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(documentSnapshot => {
* if (documentSnapshot.exists) {
* let updateTime = documentSnapshot.updateTime;
* console.log(`Document updated at '${updateTime.toDate()}'`);
* }
* });
*/
get updateTime(): Timestamp | undefined {
return this._updateTime;
}
/**
* The time this snapshot was read.
*
* @type {Timestamp}
* @name DocumentSnapshot#readTime
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(documentSnapshot => {
* let readTime = documentSnapshot.readTime;
* console.log(`Document read at '${readTime.toDate()}'`);
* });
*/
get readTime(): Timestamp {
if (this._readTime === undefined) {
throw new Error(`Called 'readTime' on a local document`);
}
return this._readTime;
}
/**
* Retrieves all fields in the document as an object. Returns 'undefined' if
* the document doesn't exist.
*
* @returns {DocumentData|undefined} An object containing all fields in the
* document or 'undefined' if the document doesn't exist.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(documentSnapshot => {
* let data = documentSnapshot.data();
* console.log(`Retrieved data: ${JSON.stringify(data)}`);
* });
*/
// We deliberately use `any` in the external API to not impose type-checking
// on end users.
data(): T | undefined {
const fields = this._fieldsProto;
if (fields === undefined) {
return undefined;
}
const obj: DocumentData = {};
for (const prop of Object.keys(fields)) {
obj[prop] = this._serializer.decodeValue(fields[prop]);
}
return this.ref._converter.fromFirestore(obj);
}
/**
* Retrieves the field specified by `field`.
*
* @param {string|FieldPath} field The field path
* (e.g. 'foo' or 'foo.bar') to a specific field.
* @returns {*} The data at the specified field location or undefined if no
* such field exists.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.set({ a: { b: 'c' }}).then(() => {
* return documentRef.get();
* }).then(documentSnapshot => {
* let field = documentSnapshot.get('a.b');
* console.log(`Retrieved field value: ${field}`);
* });
*/
// We deliberately use `any` in the external API to not impose type-checking
// on end users.
// tslint:disable-next-line no-any
get(field: string | FieldPath): any {
// tslint:disable-line no-any
validateFieldPath('field', field);
const protoField = this.protoField(field);
if (protoField === undefined) {
return undefined;
}
return this._serializer.decodeValue(protoField);
}
/**
* Retrieves the field specified by 'fieldPath' in its Protobuf JS
* representation.
*
* @private
* @param field The path (e.g. 'foo' or 'foo.bar') to a specific field.
* @returns The Protobuf-encoded data at the specified field location or
* undefined if no such field exists.
*/
protoField(field: string | FieldPath): api.IValue | undefined {
let fields: ApiMapValue | api.IValue | undefined = this._fieldsProto;
if (fields === undefined) {
return undefined;
}
const components = FieldPath.fromArgument(field).toArray();
while (components.length > 1) {
fields = (fields as ApiMapValue)[components.shift()!];
if (!fields || !fields.mapValue) {
return undefined;
}
fields = fields.mapValue.fields!;
}
return (fields as ApiMapValue)[components[0]];
}
/**
* Checks whether this DocumentSnapshot contains any fields.
*
* @private
* @return {boolean}
*/
get isEmpty(): boolean {
return this._fieldsProto === undefined || isEmpty(this._fieldsProto);
}
/**
* Convert a document snapshot to the Firestore 'Document' Protobuf.
*
* @private
* @returns The document in the format the API expects.
*/
toProto(): api.IWrite {
return {
update: {
name: this._ref.formattedName,
fields: this._fieldsProto,
},
};
}
/**
* Returns true if the document's data and path in this `DocumentSnapshot` is
* equal to the provided value.
*
* @param {*} other The value to compare against.
* @return {boolean} true if this `DocumentSnapshot` is equal to the provided
* value.
*/
isEqual(other: DocumentSnapshot<T>): boolean {
// Since the read time is different on every document read, we explicitly
// ignore all document metadata in this comparison.
return (
this === other ||
(other instanceof DocumentSnapshot &&
this._ref.isEqual(other._ref) &&
deepEqual(this._fieldsProto, other._fieldsProto, {strict: true}))
);
}
}
/**
* A QueryDocumentSnapshot contains data read from a document in your
* Firestore database as part of a query. The document is guaranteed to exist
* and its data can be extracted with [data()]{@link QueryDocumentSnapshot#data}
* or [get()]{@link DocumentSnapshot#get} to get a specific field.
*
* A QueryDocumentSnapshot offers the same API surface as a
* {@link DocumentSnapshot}. Since query results contain only existing
* documents, the [exists]{@link DocumentSnapshot#exists} property will
* always be true and [data()]{@link QueryDocumentSnapshot#data} will never
* return 'undefined'.
*
* @class
* @extends DocumentSnapshot
*/
export class QueryDocumentSnapshot<T = DocumentData> extends DocumentSnapshot<
T
> {
/**
* @hideconstructor
*
* @param ref The reference to the document.
* @param fieldsProto The fields of the Firestore `Document` Protobuf backing
* this document.
* @param readTime The time when this snapshot was read.
* @param createTime The time when the document was created.
* @param updateTime The time when the document was last updated.
*/
constructor(
ref: DocumentReference<T>,
fieldsProto: ApiMapValue,
readTime: Timestamp,
createTime: Timestamp,
updateTime: Timestamp
) {
super(ref, fieldsProto, readTime, createTime, updateTime);
}
/**
* The time the document was created.
*
* @type {Timestamp}
* @name QueryDocumentSnapshot#createTime
* @readonly
* @override
*
* @example
* let query = firestore.collection('col');
*
* query.get().forEach(snapshot => {
* console.log(`Document created at '${snapshot.createTime.toDate()}'`);
* });
*/
get createTime(): Timestamp {
return super.createTime!;
}
/**
* The time the document was last updated (at the time the snapshot was
* generated).
*
* @type {Timestamp}
* @name QueryDocumentSnapshot#updateTime
* @readonly
* @override
*
* @example
* let query = firestore.collection('col');
*
* query.get().forEach(snapshot => {
* console.log(`Document updated at '${snapshot.updateTime.toDate()}'`);
* });
*/
get updateTime(): Timestamp {
return super.updateTime!;
}
/**
* Retrieves all fields in the document as an object.
*
* @override
*
* @returns {T} An object containing all fields in the document.
*
* @example
* let query = firestore.collection('col');
*
* query.get().forEach(documentSnapshot => {
* let data = documentSnapshot.data();
* console.log(`Retrieved data: ${JSON.stringify(data)}`);
* });
*/
data(): T {
const data = super.data();
if (!data) {
throw new Error(
'The data in a QueryDocumentSnapshot should always exist.'
);
}
return data;
}
}
/**
* A Firestore Document Mask contains the field paths affected by an update.
*
* @class
* @private
*/
export class DocumentMask {
private _sortedPaths: FieldPath[];
/**
* @private
* @hideconstructor
*
* @param fieldPaths The field paths in this mask.
*/
constructor(fieldPaths: FieldPath[]) {
this._sortedPaths = fieldPaths;
this._sortedPaths.sort((a, b) => a.compareTo(b));
}
/**
* Creates a document mask with the field paths of a document.
*
* @private
* @param data A map with fields to modify. Only the keys are used to extract
* the document mask.
*/
static fromUpdateMap(data: UpdateMap): DocumentMask {
const fieldPaths: FieldPath[] = [];
data.forEach((value, key) => {
if (!(value instanceof FieldTransform) || value.includeInDocumentMask) {
fieldPaths.push(FieldPath.fromArgument(key));
}
});
return new DocumentMask(fieldPaths);
}
/**
* Creates a document mask from an array of field paths.
*
* @private
* @param fieldMask A list of field paths.
*/
static fromFieldMask(fieldMask: Array<string | FieldPath>): DocumentMask {
const fieldPaths: FieldPath[] = [];
for (const fieldPath of fieldMask) {
fieldPaths.push(FieldPath.fromArgument(fieldPath));
}
return new DocumentMask(fieldPaths);
}
/**
* Creates a document mask with the field names of a document.
*
* @private
* @param data An object with fields to modify. Only the keys are used to
* extract the document mask.
*/
static fromObject(data: DocumentData): DocumentMask {
const fieldPaths: FieldPath[] = [];
function extractFieldPaths(
currentData: DocumentData,
currentPath?: FieldPath
): void {
let isEmpty = true;
for (const key of Object.keys(currentData)) {
isEmpty = false;
// We don't split on dots since fromObject is called with
// DocumentData.
const childSegment = new FieldPath(key);
const childPath = currentPath
? currentPath.append(childSegment)
: childSegment;
const value = currentData[key];
if (value instanceof FieldTransform) {
if (value.includeInDocumentMask) {
fieldPaths.push(childPath);
}
} else if (isPlainObject(value)) {
extractFieldPaths(value, childPath);
} else {
fieldPaths.push(childPath);
}
}
// Add a field path for an explicitly updated empty map.
if (currentPath && isEmpty) {
fieldPaths.push(currentPath);
}
}
extractFieldPaths(data);
return new DocumentMask(fieldPaths);
}
/**
* Returns true if this document mask contains no fields.
*
* @private
* @return {boolean} Whether this document mask is empty.
*/
get isEmpty() {
return this._sortedPaths.length === 0;
}
/**
* Removes the specified values from a sorted field path array.
*
* @private
* @param input A sorted array of FieldPaths.
* @param values An array of FieldPaths to remove.
*/
private static removeFromSortedArray(
input: FieldPath[],
values: FieldPath[]
): void {
for (let i = 0; i < input.length; ) {
let removed = false;
for (const fieldPath of values) {
if (input[i].isEqual(fieldPath)) {
input.splice(i, 1);
removed = true;
break;
}
}
if (!removed) {
++i;
}
}
}
/**
* Removes the field path specified in 'fieldPaths' from this document mask.
*
* @private
* @param fieldPaths An array of FieldPaths.
*/
removeFields(fieldPaths: FieldPath[]): void {
DocumentMask.removeFromSortedArray(this._sortedPaths, fieldPaths);
}
/**
* Returns whether this document mask contains 'fieldPath'.
*
* @private
* @param fieldPath The field path to test.
* @return Whether this document mask contains 'fieldPath'.
*/
contains(fieldPath: FieldPath): boolean {
for (const sortedPath of this._sortedPaths) {
const cmp = sortedPath.compareTo(fieldPath);
if (cmp === 0) {
return true;
} else if (cmp > 0) {
return false;
}
}
return false;
}
/**
* Removes all properties from 'data' that are not contained in this document
* mask.
*
* @private
* @param data An object to filter.
* @return A shallow copy of the object filtered by this document mask.
*/
applyTo(data: DocumentData): DocumentData {
/*!
* Applies this DocumentMask to 'data' and computes the list of field paths
* that were specified in the mask but are not present in 'data'.
*/
const applyDocumentMask = (data: DocumentData) => {
const remainingPaths = this._sortedPaths.slice(0);
const processObject = (
currentData: DocumentData,
currentPath?: FieldPath
) => {
let result: DocumentData | null = null;
Object.keys(currentData).forEach(key => {
const childPath = currentPath
? currentPath.append(key)
: new FieldPath(key);
if (this.contains(childPath)) {
DocumentMask.removeFromSortedArray(remainingPaths, [childPath]);
result = result || {};
result[key] = currentData[key];
} else if (isObject(currentData[key])) {
const childObject = processObject(
currentData[key] as DocumentData,
childPath
);
if (childObject) {
result = result || {};
result[key] = childObject;
}
}
});
return result;
};
// processObject() returns 'null' if the DocumentMask is empty.
const filteredData = processObject(data) || {};
return {
filteredData,
remainingPaths,
};
};
const result = applyDocumentMask(data);
if (result.remainingPaths.length !== 0) {
throw new Error(
`Input data is missing for field "${result.remainingPaths[0]}".`
);
}
return result.filteredData;
}
/**
* Converts a document mask to the Firestore 'DocumentMask' Proto.
*
* @private
* @returns A Firestore 'DocumentMask' Proto.
*/
toProto(): api.IDocumentMask {
if (this.isEmpty) {
return {};
}
const encodedPaths: string[] = [];
for (const fieldPath of this._sortedPaths) {
encodedPaths.push(fieldPath.formattedName);
}
return {
fieldPaths: encodedPaths,
};
}
}
/**
* A Firestore Document Transform.
*
* A DocumentTransform contains pending server-side transforms and their
* corresponding field paths.
*
* @private
* @class
*/
export class DocumentTransform<T = DocumentData> {
/**
* @private
* @hideconstructor
*
* @param ref The DocumentReference for this transform.
* @param transforms A Map of FieldPaths to FieldTransforms.
*/
constructor(
private readonly ref: DocumentReference<T>,
private readonly transforms: Map<FieldPath, FieldTransform>
) {}
/**
* Generates a DocumentTransform from a JavaScript object.
*
* @private
* @param ref The `DocumentReference` to use for the DocumentTransform.
* @param obj The object to extract the transformations from.
* @returns The Document Transform.
*/
static fromObject<T>(
ref: DocumentReference<T>,
obj: DocumentData
): DocumentTransform<T> {
const updateMap = new Map<FieldPath, unknown>();
for (const prop of Object.keys(obj)) {
updateMap.set(new FieldPath(prop), obj[prop]);
}
return DocumentTransform.fromUpdateMap(ref, updateMap);
}
/**
* Generates a DocumentTransform from an Update Map.
*
* @private
* @param ref The `DocumentReference` to use for the DocumentTransform.
* @param data The update data to extract the transformations from.
* @returns The Document Transform.
*/
static fromUpdateMap<T>(
ref: DocumentReference<T>,
data: UpdateMap
): DocumentTransform<T> {
const transforms = new Map<FieldPath, FieldTransform>();
function encode_(val: unknown, path: FieldPath, allowTransforms: boolean) {
if (val instanceof FieldTransform && val.includeInDocumentTransform) {
if (allowTransforms) {
transforms.set(path, val);
} else {
throw new Error(
`${val.methodName}() is not supported inside of array values.`
);
}
} else if (Array.isArray(val)) {
for (let i = 0; i < val.length; ++i) {
// We need to verify that no array value contains a document transform
encode_(val[i], path.append(String(i)), false);
}
} else if (isPlainObject(val)) {
for (const prop of Object.keys(val)) {
encode_(val[prop], path.append(new FieldPath(prop)), allowTransforms);
}
}
}
data.forEach((value, key) => {
encode_(value, FieldPath.fromArgument(key), true);
});
return new DocumentTransform(ref, transforms);
}
/**
* Whether this DocumentTransform contains any actionable transformations.
*
* @private
*/
get isEmpty(): boolean {
return this.transforms.size === 0;
}
/**
* Returns the array of fields in this DocumentTransform.
*
* @private
*/
get fields(): FieldPath[] {
return Array.from(this.transforms.keys());
}
/**
* Validates the user provided field values in this document transform.
* @private
*/
validate(): void {
this.transforms.forEach(transform => transform.validate());
}
/**
* Converts a document transform to the Firestore 'DocumentTransform' Proto.
*
* @private
* @param serializer The Firestore serializer
* @returns A Firestore 'DocumentTransform' Proto or 'null' if this transform
* is empty.
*/
toProto(serializer: Serializer): api.IWrite | null {
if (this.isEmpty) {
return null;
}