-
Notifications
You must be signed in to change notification settings - Fork 145
/
write-batch.ts
970 lines (870 loc) · 27.5 KB
/
write-batch.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
/*!
* 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.
*/
import * as assert from 'assert';
import {describe, it} from 'mocha';
import {google} from '../protos/firestore_v1_proto_api';
import {
DocumentMask,
DocumentSnapshot,
DocumentTransform,
Precondition,
} from './document';
import {Firestore} from './index';
import {logger} from './logger';
import {FieldPath, validateFieldPath} from './path';
import {DocumentReference, validateDocumentReference} from './reference';
import {Serializer, validateUserInput} from './serializer';
import {Timestamp} from './timestamp';
import {
Precondition as PublicPrecondition,
SetOptions,
UpdateData,
UpdateMap,
} from './types';
import {DocumentData} from './types';
import {isObject, isPlainObject, requestTag, wrapError} from './util';
import {
customObjectMessage,
invalidArgumentMessage,
RequiredArgumentOptions,
validateMaxNumberOfArguments,
validateMinNumberOfArguments,
validateOptional,
} from './validate';
import api = google.firestore.v1;
import {GoogleError, Status} from 'google-gax';
/*!
* Google Cloud Functions terminates idle connections after two minutes. After
* longer periods of idleness, we issue transactional commits to allow for
* retries.
*/
const GCF_IDLE_TIMEOUT_MS = 110 * 1000;
/**
* A WriteResult wraps the write time set by the Firestore servers on sets(),
* updates(), and creates().
*
* @class
*/
export class WriteResult {
/**
* @hideconstructor
*
* @param _writeTime The time of the corresponding document write.
*/
constructor(private readonly _writeTime: Timestamp) {}
/**
* The write time as set by the Firestore servers.
*
* @type {Timestamp}
* @name WriteResult#writeTime
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.set({foo: 'bar'}).then(writeResult => {
* console.log(`Document written at: ${writeResult.writeTime.toDate()}`);
* });
*/
get writeTime(): Timestamp {
return this._writeTime;
}
/**
* Returns true if this `WriteResult` is equal to the provided value.
*
* @param {*} other The value to compare against.
* @return true if this `WriteResult` is equal to the provided value.
*/
isEqual(other: WriteResult): boolean {
return (
this === other ||
(other instanceof WriteResult &&
this._writeTime.isEqual(other._writeTime))
);
}
}
/**
* A BatchWriteResult wraps the write time and status returned by Firestore
* when making BatchWriteRequests.
*
* @private
*/
export class BatchWriteResult {
constructor(
readonly writeTime: Timestamp | null,
readonly status: GoogleError
) {}
}
/** Helper type to manage the list of writes in a WriteBatch. */
// TODO(mrschmidt): Replace with api.IWrite
interface WriteOp {
write: api.IWrite;
precondition?: api.IPrecondition | null;
}
/**
* A Firestore WriteBatch that can be used to atomically commit multiple write
* operations at once.
*
* @class
*/
export class WriteBatch {
private readonly _firestore: Firestore;
private readonly _serializer: Serializer;
private readonly _allowUndefined: boolean;
/**
* An array of write operations that are executed as part of the commit. The
* resulting `api.IWrite` will be sent to the backend.
* @private
*/
private readonly _ops: Array<() => WriteOp> = [];
private _committed = false;
/**
* @hideconstructor
*
* @param firestore The Firestore Database client.
*/
constructor(firestore: Firestore) {
this._firestore = firestore;
this._serializer = new Serializer(firestore);
this._allowUndefined = !!firestore._settings.ignoreUndefinedProperties;
}
/**
* Checks if this write batch has any pending operations.
*
* @private
*/
get isEmpty(): boolean {
return this._ops.length === 0;
}
/**
* Throws an error if this batch has already been committed.
*
* @private
*/
private verifyNotCommitted(): void {
if (this._committed) {
throw new Error('Cannot modify a WriteBatch that has been committed.');
}
}
/**
* Create a document with the provided object values. This will fail the batch
* if a document exists at its location.
*
* @param {DocumentReference} documentRef A reference to the document to be
* created.
* @param {T} data The object to serialize as the document.
* @returns {WriteBatch} This WriteBatch instance. Used for chaining
* method calls.
*
* @example
* let writeBatch = firestore.batch();
* let documentRef = firestore.collection('col').doc();
*
* writeBatch.create(documentRef, {foo: 'bar'});
*
* writeBatch.commit().then(() => {
* console.log('Successfully executed batch.');
* });
*/
create<T>(documentRef: DocumentReference<T>, data: T): WriteBatch {
validateDocumentReference('documentRef', documentRef);
const firestoreData = documentRef._converter.toFirestore(data);
validateDocumentData(
'data',
firestoreData,
/* allowDeletes= */ false,
this._allowUndefined
);
this.verifyNotCommitted();
const transform = DocumentTransform.fromObject(documentRef, firestoreData);
transform.validate();
const precondition = new Precondition({exists: false});
const op = () => {
const document = DocumentSnapshot.fromObject(documentRef, firestoreData);
const write = document.toProto();
if (!transform.isEmpty) {
write.updateTransforms = transform.toProto(this._serializer);
}
return {
write,
precondition: precondition.toProto(),
};
};
this._ops.push(op);
return this;
}
/**
* Deletes a document from the database.
*
* @param {DocumentReference} documentRef A reference to the document to be
* deleted.
* @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 batch if the
* document doesn't exist or was last updated at a different time.
* @returns {WriteBatch} This WriteBatch instance. Used for chaining
* method calls.
*
* @example
* let writeBatch = firestore.batch();
* let documentRef = firestore.doc('col/doc');
*
* writeBatch.delete(documentRef);
*
* writeBatch.commit().then(() => {
* console.log('Successfully executed batch.');
* });
*/
delete<T>(
documentRef: DocumentReference<T>,
precondition?: PublicPrecondition
): WriteBatch {
validateDocumentReference('documentRef', documentRef);
validateDeletePrecondition('precondition', precondition, {optional: true});
this.verifyNotCommitted();
const conditions = new Precondition(precondition);
const op = () => {
return {
write: {
delete: documentRef.formattedName,
},
precondition: conditions.toProto(),
};
};
this._ops.push(op);
return this;
}
/**
* Write to the document referred to by the provided
* [DocumentReference]{@link DocumentReference}.
* If the document does not exist yet, it will be created. If you pass
* [SetOptions]{@link SetOptions}., the provided data can be merged
* into the existing document.
*
* @param {DocumentReference} documentRef A reference to the document to be
* set.
* @param {T} data The object to serialize as 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 {WriteBatch} This WriteBatch instance. Used for chaining
* method calls.
*
* @example
* let writeBatch = firestore.batch();
* let documentRef = firestore.doc('col/doc');
*
* writeBatch.set(documentRef, {foo: 'bar'});
*
* writeBatch.commit().then(() => {
* console.log('Successfully executed batch.');
* });
*/
set<T>(
documentRef: DocumentReference<T>,
data: T,
options?: SetOptions
): WriteBatch {
validateSetOptions('options', options, {optional: true});
const mergeLeaves = options && options.merge === true;
const mergePaths = options && options.mergeFields;
validateDocumentReference('documentRef', documentRef);
let firestoreData = documentRef._converter.toFirestore(data);
validateDocumentData(
'data',
firestoreData,
/* allowDeletes= */ !!(mergePaths || mergeLeaves),
this._allowUndefined
);
this.verifyNotCommitted();
let documentMask: DocumentMask;
if (mergePaths) {
documentMask = DocumentMask.fromFieldMask(options!.mergeFields!);
firestoreData = documentMask.applyTo(firestoreData);
}
const transform = DocumentTransform.fromObject(documentRef, firestoreData);
transform.validate();
const op = () => {
const document = DocumentSnapshot.fromObject(documentRef, firestoreData);
if (mergePaths) {
documentMask!.removeFields(transform.fields);
} else if (mergeLeaves) {
documentMask = DocumentMask.fromObject(firestoreData);
}
const write = document.toProto();
if (!transform.isEmpty) {
write.updateTransforms = transform.toProto(this._serializer);
}
if (mergePaths || mergeLeaves) {
write.updateMask = documentMask!.toProto();
}
return {
write,
};
};
this._ops.push(op);
return this;
}
/**
* Update fields of the document referred to by the provided
* [DocumentReference]{@link DocumentReference}. If the document
* doesn't yet exist, the update fails and the entire batch 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. Nested fields can be
* updated by providing dot-separated field path strings or by providing
* FieldPath objects.
*
* A Precondition restricting this update can be specified as the last
* argument.
*
* @param {DocumentReference} documentRef A reference to the document to be
* updated.
* @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 {
* ...(Precondition|*|string|FieldPath)} preconditionOrValues -
* An alternating list of field paths and values to update or a Precondition
* to restrict this update.
* @returns {WriteBatch} This WriteBatch instance. Used for chaining
* method calls.
*
* @example
* let writeBatch = firestore.batch();
* let documentRef = firestore.doc('col/doc');
*
* writeBatch.update(documentRef, {foo: 'bar'});
*
* writeBatch.commit().then(() => {
* console.log('Successfully executed batch.');
* });
*/
update<T = DocumentData>(
documentRef: DocumentReference<T>,
dataOrField: UpdateData | string | FieldPath,
...preconditionOrValues: Array<
{lastUpdateTime?: Timestamp} | unknown | string | FieldPath
>
): WriteBatch {
validateMinNumberOfArguments('WriteBatch.update', arguments, 2);
validateDocumentReference('documentRef', documentRef);
this.verifyNotCommitted();
const updateMap = new Map<FieldPath, unknown>();
let precondition = new Precondition({exists: true});
const argumentError =
'Update() requires either a single JavaScript ' +
'object or an alternating list of field/value pairs that can be ' +
'followed by an optional precondition.';
const usesVarargs =
typeof dataOrField === 'string' || dataOrField instanceof FieldPath;
if (usesVarargs) {
try {
for (let i = 1; i < arguments.length; i += 2) {
if (i === arguments.length - 1) {
validateUpdatePrecondition(i, arguments[i]);
precondition = new Precondition(arguments[i]);
} else {
validateFieldPath(i, arguments[i]);
// Unlike the `validateMinNumberOfArguments` invocation above, this
// validation can be triggered both from `WriteBatch.update()` and
// `DocumentReference.update()`. Hence, we don't use the fully
// qualified API name in the error message.
validateMinNumberOfArguments('update', arguments, i + 1);
const fieldPath = FieldPath.fromArgument(arguments[i]);
validateFieldValue(
i,
arguments[i + 1],
this._allowUndefined,
fieldPath
);
updateMap.set(fieldPath, arguments[i + 1]);
}
}
} catch (err) {
logger('WriteBatch.update', null, 'Varargs validation failed:', err);
// We catch the validation error here and re-throw to provide a better
// error message.
throw new Error(`${argumentError} ${err.message}`);
}
} else {
try {
validateUpdateMap('dataOrField', dataOrField, this._allowUndefined);
validateMaxNumberOfArguments('update', arguments, 3);
const data = dataOrField as UpdateData;
Object.keys(data).forEach(key => {
validateFieldPath(key, key);
updateMap.set(FieldPath.fromArgument(key), data[key]);
});
if (preconditionOrValues.length > 0) {
validateUpdatePrecondition(
'preconditionOrValues',
preconditionOrValues[0]
);
precondition = new Precondition(
preconditionOrValues[0] as {
lastUpdateTime?: Timestamp;
}
);
}
} catch (err) {
logger(
'WriteBatch.update',
null,
'Non-varargs validation failed:',
err
);
// We catch the validation error here and prefix the error with a custom
// message to describe the usage of update() better.
throw new Error(`${argumentError} ${err.message}`);
}
}
validateNoConflictingFields('dataOrField', updateMap);
const transform = DocumentTransform.fromUpdateMap(documentRef, updateMap);
transform.validate();
const documentMask = DocumentMask.fromUpdateMap(updateMap);
const op = () => {
const document = DocumentSnapshot.fromUpdateMap(documentRef, updateMap);
const write = document.toProto();
write!.updateMask = documentMask.toProto();
if (!transform.isEmpty) {
write!.updateTransforms = transform.toProto(this._serializer);
}
return {
write,
precondition: precondition.toProto(),
};
};
this._ops.push(op);
return this;
}
/**
* Atomically commits all pending operations to the database and verifies all
* preconditions. Fails the entire write if any precondition is not met.
*
* @returns {Promise.<Array.<WriteResult>>} A Promise that resolves
* when this batch completes.
*
* @example
* let writeBatch = firestore.batch();
* let documentRef = firestore.doc('col/doc');
*
* writeBatch.set(documentRef, {foo: 'bar'});
*
* writeBatch.commit().then(() => {
* console.log('Successfully executed batch.');
* });
*/
commit(): Promise<WriteResult[]> {
// Capture the error stack to preserve stack tracing across async calls.
const stack = Error().stack!;
return this.commit_().catch(err => {
throw wrapError(err, stack);
});
}
/**
* Commits all pending operations to the database and verifies all
* preconditions.
*
* The writes in the batch are not applied atomically and can be applied out
* of order.
*
* @private
*/
async bulkCommit(): Promise<BatchWriteResult[]> {
this._committed = true;
const tag = requestTag();
await this._firestore.initializeIfNeeded(tag);
const database = this._firestore.formattedName;
const request: api.IBatchWriteRequest = {database, writes: []};
const writes = this._ops.map(op => op());
for (const req of writes) {
if (req.precondition) {
req.write!.currentDocument = req.precondition;
}
request.writes!.push(req.write);
}
const response = await this._firestore.request<
api.IBatchWriteRequest,
api.BatchWriteResponse
>('batchWrite', request, tag);
return (response.writeResults || []).map((result, i) => {
const status = response.status[i];
const error = new GoogleError(status.message || undefined);
error.code = status.code as Status;
return new BatchWriteResult(
result.updateTime ? Timestamp.fromProto(result.updateTime) : null,
error
);
});
}
/**
* Commit method that takes an optional transaction ID.
*
* @private
* @param commitOptions Options to use for this commit.
* @param commitOptions.transactionId The transaction ID of this commit.
* @param commitOptions.requestTag A unique client-assigned identifier for
* this request.
* @returns A Promise that resolves when this batch completes.
*/
async commit_(commitOptions?: {
transactionId?: Uint8Array;
requestTag?: string;
}): Promise<WriteResult[]> {
// Note: We don't call `verifyNotCommitted()` to allow for retries.
this._committed = true;
const tag = (commitOptions && commitOptions.requestTag) || requestTag();
await this._firestore.initializeIfNeeded(tag);
const database = this._firestore.formattedName;
// On GCF, we periodically force transactional commits to allow for
// request retries in case GCF closes our backend connection.
const explicitTransaction = commitOptions && commitOptions.transactionId;
if (!explicitTransaction && this._shouldCreateTransaction()) {
logger('WriteBatch.commit', tag, 'Using transaction for commit');
return this._firestore
.request<api.IBeginTransactionRequest, api.IBeginTransactionResponse>(
'beginTransaction',
{database},
tag
)
.then(resp => {
return this.commit_({transactionId: resp.transaction!});
});
}
const request: api.ICommitRequest = {database, writes: []};
const writes = this._ops.map(op => op());
for (const req of writes) {
if (req.precondition) {
req.write!.currentDocument = req.precondition;
}
request.writes!.push(req.write);
}
logger(
'WriteBatch.commit',
tag,
'Sending %d writes',
request.writes!.length
);
if (explicitTransaction) {
request.transaction = explicitTransaction;
}
const response = await this._firestore.request<
api.ICommitRequest,
api.CommitResponse
>('commit', request, tag);
return (response.writeResults || []).map(
writeResult =>
new WriteResult(
Timestamp.fromProto(writeResult.updateTime || response.commitTime!)
)
);
}
/**
* Determines whether we should issue a transactional commit. On GCF, this
* happens after two minutes of idleness.
*
* @private
* @returns Whether to use a transaction.
*/
private _shouldCreateTransaction(): boolean {
if (!this._firestore._preferTransactions) {
return false;
}
if (this._firestore._lastSuccessfulRequest) {
const now = new Date().getTime();
return now - this._firestore._lastSuccessfulRequest > GCF_IDLE_TIMEOUT_MS;
}
return true;
}
/**
* Resets the WriteBatch and dequeues all pending operations.
* @private
*/
_reset() {
this._ops.splice(0);
this._committed = false;
}
}
/**
* Validates the use of 'value' as a Precondition and enforces that 'exists'
* and 'lastUpdateTime' use valid types.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The object to validate
* @param allowExists Whether to allow the 'exists' preconditions.
*/
function validatePrecondition(
arg: string | number,
value: unknown,
allowExists: boolean
): void {
if (typeof value !== 'object' || value === null) {
throw new Error('Input is not an object.');
}
const precondition = value as {[k: string]: unknown};
let conditions = 0;
if (precondition.exists !== undefined) {
++conditions;
if (!allowExists) {
throw new Error(
`${invalidArgumentMessage(
arg,
'precondition'
)} "exists" is not an allowed precondition.`
);
}
if (typeof precondition.exists !== 'boolean') {
throw new Error(
`${invalidArgumentMessage(
arg,
'precondition'
)} "exists" is not a boolean.'`
);
}
}
if (precondition.lastUpdateTime !== undefined) {
++conditions;
if (!(precondition.lastUpdateTime instanceof Timestamp)) {
throw new Error(
`${invalidArgumentMessage(
arg,
'precondition'
)} "lastUpdateTime" is not a Firestore Timestamp.`
);
}
}
if (conditions > 1) {
throw new Error(
`${invalidArgumentMessage(
arg,
'precondition'
)} Input specifies more than one precondition.`
);
}
}
/**
* Validates the use of 'value' as an update Precondition.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The object to validate.
* @param options Optional validation options specifying whether the value can
* be omitted.
*/
function validateUpdatePrecondition(
arg: string | number,
value: unknown,
options?: RequiredArgumentOptions
): void {
if (!validateOptional(value, options)) {
validatePrecondition(arg, value, /* allowExists= */ false);
}
}
/**
* Validates the use of 'value' as a delete Precondition.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The object to validate.
* @param options Optional validation options specifying whether the value can
* be omitted.
*/
function validateDeletePrecondition(
arg: string | number,
value: unknown,
options?: RequiredArgumentOptions
): void {
if (!validateOptional(value, options)) {
validatePrecondition(arg, value, /* allowExists= */ true);
}
}
/**
* Validates the use of 'value' as SetOptions and enforces that 'merge' is a
* boolean.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The object to validate.
* @param options Optional validation options specifying whether the value can
* be omitted.
* @throws if the input is not a valid SetOptions object.
*/
export function validateSetOptions(
arg: string | number,
value: unknown,
options?: RequiredArgumentOptions
): void {
if (!validateOptional(value, options)) {
if (!isObject(value)) {
throw new Error(
`${invalidArgumentMessage(
arg,
'set() options argument'
)} Input is not an object.`
);
}
const setOptions = value as {[k: string]: unknown};
if ('merge' in setOptions && typeof setOptions.merge !== 'boolean') {
throw new Error(
`${invalidArgumentMessage(
arg,
'set() options argument'
)} "merge" is not a boolean.`
);
}
if ('mergeFields' in setOptions) {
if (!Array.isArray(setOptions.mergeFields)) {
throw new Error(
`${invalidArgumentMessage(
arg,
'set() options argument'
)} "mergeFields" is not an array.`
);
}
for (let i = 0; i < setOptions.mergeFields.length; ++i) {
try {
validateFieldPath(i, setOptions.mergeFields[i]);
} catch (err) {
throw new Error(
`${invalidArgumentMessage(
arg,
'set() options argument'
)} "mergeFields" is not valid: ${err.message}`
);
}
}
}
if ('merge' in setOptions && 'mergeFields' in setOptions) {
throw new Error(
`${invalidArgumentMessage(
arg,
'set() options argument'
)} You cannot specify both "merge" and "mergeFields".`
);
}
}
}
/**
* Validates a JavaScript object for usage as a Firestore document.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param obj JavaScript object to validate.
* @param allowDeletes Whether to allow FieldValue.delete() sentinels.
* @param allowUndefined Whether to allow nested properties that are `undefined`.
* @throws when the object is invalid.
*/
export function validateDocumentData(
arg: string | number,
obj: unknown,
allowDeletes: boolean,
allowUndefined: boolean
): void {
if (!isPlainObject(obj)) {
throw new Error(customObjectMessage(arg, obj));
}
validateUserInput(arg, obj, 'Firestore document', {
allowDeletes: allowDeletes ? 'all' : 'none',
allowTransforms: true,
allowUndefined,
});
}
/**
* Validates that a value can be used as field value during an update.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param val The value to verify.
* @param allowUndefined Whether to allow nested properties that are `undefined`.
* @param path The path to show in the error message.
*/
export function validateFieldValue(
arg: string | number,
val: unknown,
allowUndefined: boolean,
path?: FieldPath
): void {
validateUserInput(
arg,
val,
'Firestore value',
{allowDeletes: 'root', allowTransforms: true, allowUndefined},
path
);
}
/**
* Validates that the update data does not contain any ambiguous field
* definitions (such as 'a.b' and 'a').
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param data An update map with field/value pairs.
*/
function validateNoConflictingFields(
arg: string | number,
data: UpdateMap
): void {
const fields: FieldPath[] = [];
data.forEach((value, key) => {
fields.push(key);
});
fields.sort((left, right) => left.compareTo(right));
for (let i = 1; i < fields.length; ++i) {
if (fields[i - 1].isPrefixOf(fields[i])) {
throw new Error(
`${invalidArgumentMessage(arg, 'update map')} Field "${
fields[i - 1]
}" was specified multiple times.`
);
}
}
}
/**
* Validates that a JavaScript object is a map of field paths to field values.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param obj JavaScript object to validate.
* @param allowUndefined Whether to allow nested properties that are `undefined`.
* @throws when the object is invalid.
*/
function validateUpdateMap(
arg: string | number,
obj: unknown,
allowUndefined: boolean
): void {
if (!isPlainObject(obj)) {
throw new Error(customObjectMessage(arg, obj));
}
let isEmpty = true;
if (obj) {
for (const prop of Object.keys(obj)) {
isEmpty = false;
validateFieldValue(arg, obj[prop], allowUndefined, new FieldPath(prop));
}
}
if (isEmpty) {
throw new Error('At least one field must be updated.');
}
}