-
Notifications
You must be signed in to change notification settings - Fork 924
/
Copy pathserializer.ts
1377 lines (1262 loc) · 40.2 KB
/
serializer.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 2017 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 { Aggregate } from '../core/aggregate';
import { Bound } from '../core/bound';
import { DatabaseId } from '../core/database_info';
import {
CompositeFilter,
compositeFilterIsFlatConjunction,
CompositeOperator,
FieldFilter,
Filter,
Operator
} from '../core/filter';
import { Direction, OrderBy } from '../core/order_by';
import {
LimitType,
newQuery,
newQueryForPath,
Query,
queryToTarget
} from '../core/query';
import { SnapshotVersion } from '../core/snapshot_version';
import { targetIsDocumentTarget, Target } from '../core/target';
import { TargetId } from '../core/types';
import { Timestamp } from '../lite-api/timestamp';
import { TargetData, TargetPurpose } from '../local/target_data';
import { MutableDocument } from '../model/document';
import { DocumentKey } from '../model/document_key';
import { FieldMask } from '../model/field_mask';
import {
DeleteMutation,
FieldTransform,
Mutation,
MutationResult,
PatchMutation,
Precondition,
SetMutation,
VerifyMutation
} from '../model/mutation';
import { normalizeTimestamp } from '../model/normalize';
import { ObjectValue } from '../model/object_value';
import { FieldPath, ResourcePath } from '../model/path';
import {
ArrayRemoveTransformOperation,
ArrayUnionTransformOperation,
NumericIncrementTransformOperation,
ServerTimestampTransform,
TransformOperation
} from '../model/transform_operation';
import { isNanValue, isNullValue } from '../model/values';
import {
ApiClientObjectMap as ProtoApiClientObjectMap,
BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse,
CompositeFilterOp as ProtoCompositeFilterOp,
Cursor as ProtoCursor,
Document as ProtoDocument,
DocumentMask as ProtoDocumentMask,
DocumentsTarget as ProtoDocumentsTarget,
FieldFilterOp as ProtoFieldFilterOp,
FieldReference as ProtoFieldReference,
FieldTransform as ProtoFieldTransform,
Filter as ProtoFilter,
ListenResponse as ProtoListenResponse,
Order as ProtoOrder,
OrderDirection as ProtoOrderDirection,
Precondition as ProtoPrecondition,
QueryTarget as ProtoQueryTarget,
RunAggregationQueryRequest as ProtoRunAggregationQueryRequest,
RunAggregationQueryResponse as ProtoRunAggregationQueryResponse,
Aggregation as ProtoAggregation,
Status as ProtoStatus,
Target as ProtoTarget,
TargetChangeTargetChangeType as ProtoTargetChangeTargetChangeType,
Timestamp as ProtoTimestamp,
Write as ProtoWrite,
WriteResult as ProtoWriteResult
} from '../protos/firestore_proto_api';
import { debugAssert, fail, hardAssert } from '../util/assert';
import { ByteString } from '../util/byte_string';
import { Code, FirestoreError } from '../util/error';
import { isNullOrUndefined } from '../util/types';
import { ExistenceFilter } from './existence_filter';
import { Serializer } from './number_serializer';
import { mapCodeFromRpcCode } from './rpc_error';
import {
DocumentWatchChange,
ExistenceFilterChange,
WatchChange,
WatchTargetChange,
WatchTargetChangeState
} from './watch_change';
const DIRECTIONS = (() => {
const dirs: { [dir: string]: ProtoOrderDirection } = {};
dirs[Direction.ASCENDING] = 'ASCENDING';
dirs[Direction.DESCENDING] = 'DESCENDING';
return dirs;
})();
const OPERATORS = (() => {
const ops: { [op: string]: ProtoFieldFilterOp } = {};
ops[Operator.LESS_THAN] = 'LESS_THAN';
ops[Operator.LESS_THAN_OR_EQUAL] = 'LESS_THAN_OR_EQUAL';
ops[Operator.GREATER_THAN] = 'GREATER_THAN';
ops[Operator.GREATER_THAN_OR_EQUAL] = 'GREATER_THAN_OR_EQUAL';
ops[Operator.EQUAL] = 'EQUAL';
ops[Operator.NOT_EQUAL] = 'NOT_EQUAL';
ops[Operator.ARRAY_CONTAINS] = 'ARRAY_CONTAINS';
ops[Operator.IN] = 'IN';
ops[Operator.NOT_IN] = 'NOT_IN';
ops[Operator.ARRAY_CONTAINS_ANY] = 'ARRAY_CONTAINS_ANY';
return ops;
})();
const COMPOSITE_OPERATORS = (() => {
const ops: { [op: string]: ProtoCompositeFilterOp } = {};
ops[CompositeOperator.AND] = 'AND';
ops[CompositeOperator.OR] = 'OR';
return ops;
})();
function assertPresent(value: unknown, description: string): asserts value {
debugAssert(!isNullOrUndefined(value), description + ' is missing');
}
/**
* This class generates JsonObject values for the Datastore API suitable for
* sending to either GRPC stub methods or via the JSON/HTTP REST API.
*
* The serializer supports both Protobuf.js and Proto3 JSON formats. By
* setting `useProto3Json` to true, the serializer will use the Proto3 JSON
* format.
*
* For a description of the Proto3 JSON format check
* https://developers.google.com/protocol-buffers/docs/proto3#json
*
* TODO(klimt): We can remove the databaseId argument if we keep the full
* resource name in documents.
*/
export class JsonProtoSerializer implements Serializer {
constructor(
readonly databaseId: DatabaseId,
readonly useProto3Json: boolean
) {}
}
function fromRpcStatus(status: ProtoStatus): FirestoreError {
const code =
status.code === undefined ? Code.UNKNOWN : mapCodeFromRpcCode(status.code);
return new FirestoreError(code, status.message || '');
}
/**
* Returns a value for a number (or null) that's appropriate to put into
* a google.protobuf.Int32Value proto.
* DO NOT USE THIS FOR ANYTHING ELSE.
* This method cheats. It's typed as returning "number" because that's what
* our generated proto interfaces say Int32Value must be. But GRPC actually
* expects a { value: <number> } struct.
*/
function toInt32Proto(
serializer: JsonProtoSerializer,
val: number | null
): number | { value: number } | null {
if (serializer.useProto3Json || isNullOrUndefined(val)) {
return val;
} else {
return { value: val };
}
}
/**
* Returns a number (or null) from a google.protobuf.Int32Value proto.
*/
function fromInt32Proto(
val: number | { value: number } | undefined
): number | null {
let result;
if (typeof val === 'object') {
result = val.value;
} else {
result = val;
}
return isNullOrUndefined(result) ? null : result;
}
/**
* Returns a value for a Date that's appropriate to put into a proto.
*/
export function toTimestamp(
serializer: JsonProtoSerializer,
timestamp: Timestamp
): ProtoTimestamp {
if (serializer.useProto3Json) {
// Serialize to ISO-8601 date format, but with full nano resolution.
// Since JS Date has only millis, let's only use it for the seconds and
// then manually add the fractions to the end.
const jsDateStr = new Date(timestamp.seconds * 1000).toISOString();
// Remove .xxx frac part and Z in the end.
const strUntilSeconds = jsDateStr.replace(/\.\d*/, '').replace('Z', '');
// Pad the fraction out to 9 digits (nanos).
const nanoStr = ('000000000' + timestamp.nanoseconds).slice(-9);
return `${strUntilSeconds}.${nanoStr}Z`;
} else {
return {
seconds: '' + timestamp.seconds,
nanos: timestamp.nanoseconds
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any;
}
}
function fromTimestamp(date: ProtoTimestamp): Timestamp {
const timestamp = normalizeTimestamp(date);
return new Timestamp(timestamp.seconds, timestamp.nanos);
}
/**
* Returns a value for bytes that's appropriate to put in a proto.
*
* Visible for testing.
*/
export function toBytes(
serializer: JsonProtoSerializer,
bytes: ByteString
): string | Uint8Array {
if (serializer.useProto3Json) {
return bytes.toBase64();
} else {
return bytes.toUint8Array();
}
}
/**
* Returns a ByteString based on the proto string value.
*/
export function fromBytes(
serializer: JsonProtoSerializer,
value: string | Uint8Array | undefined
): ByteString {
if (serializer.useProto3Json) {
hardAssert(
value === undefined || typeof value === 'string',
'value must be undefined or a string when using proto3 Json'
);
return ByteString.fromBase64String(value ? value : '');
} else {
hardAssert(
value === undefined || value instanceof Uint8Array,
'value must be undefined or Uint8Array'
);
return ByteString.fromUint8Array(value ? value : new Uint8Array());
}
}
export function toVersion(
serializer: JsonProtoSerializer,
version: SnapshotVersion
): ProtoTimestamp {
return toTimestamp(serializer, version.toTimestamp());
}
export function fromVersion(version: ProtoTimestamp): SnapshotVersion {
hardAssert(!!version, "Trying to deserialize version that isn't set");
return SnapshotVersion.fromTimestamp(fromTimestamp(version));
}
export function toResourceName(
databaseId: DatabaseId,
path: ResourcePath
): string {
return fullyQualifiedPrefixPath(databaseId)
.child('documents')
.child(path)
.canonicalString();
}
function fromResourceName(name: string): ResourcePath {
const resource = ResourcePath.fromString(name);
hardAssert(
isValidResourceName(resource),
'Tried to deserialize invalid key ' + resource.toString()
);
return resource;
}
export function toName(
serializer: JsonProtoSerializer,
key: DocumentKey
): string {
return toResourceName(serializer.databaseId, key.path);
}
export function fromName(
serializer: JsonProtoSerializer,
name: string
): DocumentKey {
const resource = fromResourceName(name);
if (resource.get(1) !== serializer.databaseId.projectId) {
throw new FirestoreError(
Code.INVALID_ARGUMENT,
'Tried to deserialize key from different project: ' +
resource.get(1) +
' vs ' +
serializer.databaseId.projectId
);
}
if (resource.get(3) !== serializer.databaseId.database) {
throw new FirestoreError(
Code.INVALID_ARGUMENT,
'Tried to deserialize key from different database: ' +
resource.get(3) +
' vs ' +
serializer.databaseId.database
);
}
return new DocumentKey(extractLocalPathFromResourceName(resource));
}
function toQueryPath(
serializer: JsonProtoSerializer,
path: ResourcePath
): string {
return toResourceName(serializer.databaseId, path);
}
function fromQueryPath(name: string): ResourcePath {
const resourceName = fromResourceName(name);
// In v1beta1 queries for collections at the root did not have a trailing
// "/documents". In v1 all resource paths contain "/documents". Preserve the
// ability to read the v1beta1 form for compatibility with queries persisted
// in the local target cache.
if (resourceName.length === 4) {
return ResourcePath.emptyPath();
}
return extractLocalPathFromResourceName(resourceName);
}
export function getEncodedDatabaseId(serializer: JsonProtoSerializer): string {
const path = new ResourcePath([
'projects',
serializer.databaseId.projectId,
'databases',
serializer.databaseId.database
]);
return path.canonicalString();
}
function fullyQualifiedPrefixPath(databaseId: DatabaseId): ResourcePath {
return new ResourcePath([
'projects',
databaseId.projectId,
'databases',
databaseId.database
]);
}
function extractLocalPathFromResourceName(
resourceName: ResourcePath
): ResourcePath {
hardAssert(
resourceName.length > 4 && resourceName.get(4) === 'documents',
'tried to deserialize invalid key ' + resourceName.toString()
);
return resourceName.popFirst(5);
}
/** Creates a Document proto from key and fields (but no create/update time) */
export function toMutationDocument(
serializer: JsonProtoSerializer,
key: DocumentKey,
fields: ObjectValue
): ProtoDocument {
return {
name: toName(serializer, key),
fields: fields.value.mapValue.fields
};
}
export function toDocument(
serializer: JsonProtoSerializer,
document: MutableDocument
): ProtoDocument {
debugAssert(
!document.hasLocalMutations,
"Can't serialize documents with mutations."
);
return {
name: toName(serializer, document.key),
fields: document.data.value.mapValue.fields,
updateTime: toTimestamp(serializer, document.version.toTimestamp()),
createTime: toTimestamp(serializer, document.createTime.toTimestamp())
};
}
export function fromDocument(
serializer: JsonProtoSerializer,
document: ProtoDocument,
hasCommittedMutations?: boolean
): MutableDocument {
const key = fromName(serializer, document.name!);
const version = fromVersion(document.updateTime!);
// If we read a document from persistence that is missing createTime, it's due
// to older SDK versions not storing this information. In such cases, we'll
// set the createTime to zero. This can be removed in the long term.
const createTime = document.createTime
? fromVersion(document.createTime)
: SnapshotVersion.min();
const data = new ObjectValue({ mapValue: { fields: document.fields } });
const result = MutableDocument.newFoundDocument(
key,
version,
createTime,
data
);
if (hasCommittedMutations) {
result.setHasCommittedMutations();
}
return hasCommittedMutations ? result.setHasCommittedMutations() : result;
}
export function fromAggregationResult(
aggregationQueryResponse: ProtoRunAggregationQueryResponse
): ObjectValue {
assertPresent(
aggregationQueryResponse.result,
'aggregationQueryResponse.result'
);
assertPresent(
aggregationQueryResponse.result.aggregateFields,
'aggregationQueryResponse.result.aggregateFields'
);
return new ObjectValue({
mapValue: { fields: aggregationQueryResponse.result?.aggregateFields }
});
}
function fromFound(
serializer: JsonProtoSerializer,
doc: ProtoBatchGetDocumentsResponse
): MutableDocument {
hardAssert(
!!doc.found,
'Tried to deserialize a found document from a missing document.'
);
assertPresent(doc.found.name, 'doc.found.name');
assertPresent(doc.found.updateTime, 'doc.found.updateTime');
const key = fromName(serializer, doc.found.name);
const version = fromVersion(doc.found.updateTime);
const createTime = doc.found.createTime
? fromVersion(doc.found.createTime)
: SnapshotVersion.min();
const data = new ObjectValue({ mapValue: { fields: doc.found.fields } });
return MutableDocument.newFoundDocument(key, version, createTime, data);
}
function fromMissing(
serializer: JsonProtoSerializer,
result: ProtoBatchGetDocumentsResponse
): MutableDocument {
hardAssert(
!!result.missing,
'Tried to deserialize a missing document from a found document.'
);
hardAssert(
!!result.readTime,
'Tried to deserialize a missing document without a read time.'
);
const key = fromName(serializer, result.missing);
const version = fromVersion(result.readTime);
return MutableDocument.newNoDocument(key, version);
}
export function fromBatchGetDocumentsResponse(
serializer: JsonProtoSerializer,
result: ProtoBatchGetDocumentsResponse
): MutableDocument {
if ('found' in result) {
return fromFound(serializer, result);
} else if ('missing' in result) {
return fromMissing(serializer, result);
}
return fail('invalid batch get response: ' + JSON.stringify(result));
}
export function fromWatchChange(
serializer: JsonProtoSerializer,
change: ProtoListenResponse
): WatchChange {
let watchChange: WatchChange;
if ('targetChange' in change) {
assertPresent(change.targetChange, 'targetChange');
// proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'
// if unset
const state = fromWatchTargetChangeState(
change.targetChange.targetChangeType || 'NO_CHANGE'
);
const targetIds: TargetId[] = change.targetChange.targetIds || [];
const resumeToken = fromBytes(serializer, change.targetChange.resumeToken);
const causeProto = change.targetChange!.cause;
const cause = causeProto && fromRpcStatus(causeProto);
watchChange = new WatchTargetChange(
state,
targetIds,
resumeToken,
cause || null
);
} else if ('documentChange' in change) {
assertPresent(change.documentChange, 'documentChange');
const entityChange = change.documentChange;
assertPresent(entityChange.document, 'documentChange.name');
assertPresent(entityChange.document.name, 'documentChange.document.name');
assertPresent(
entityChange.document.updateTime,
'documentChange.document.updateTime'
);
const key = fromName(serializer, entityChange.document.name);
const version = fromVersion(entityChange.document.updateTime);
const createTime = entityChange.document.createTime
? fromVersion(entityChange.document.createTime)
: SnapshotVersion.min();
const data = new ObjectValue({
mapValue: { fields: entityChange.document.fields }
});
const doc = MutableDocument.newFoundDocument(
key,
version,
createTime,
data
);
const updatedTargetIds = entityChange.targetIds || [];
const removedTargetIds = entityChange.removedTargetIds || [];
watchChange = new DocumentWatchChange(
updatedTargetIds,
removedTargetIds,
doc.key,
doc
);
} else if ('documentDelete' in change) {
assertPresent(change.documentDelete, 'documentDelete');
const docDelete = change.documentDelete;
assertPresent(docDelete.document, 'documentDelete.document');
const key = fromName(serializer, docDelete.document);
const version = docDelete.readTime
? fromVersion(docDelete.readTime)
: SnapshotVersion.min();
const doc = MutableDocument.newNoDocument(key, version);
const removedTargetIds = docDelete.removedTargetIds || [];
watchChange = new DocumentWatchChange([], removedTargetIds, doc.key, doc);
} else if ('documentRemove' in change) {
assertPresent(change.documentRemove, 'documentRemove');
const docRemove = change.documentRemove;
assertPresent(docRemove.document, 'documentRemove');
const key = fromName(serializer, docRemove.document);
const removedTargetIds = docRemove.removedTargetIds || [];
watchChange = new DocumentWatchChange([], removedTargetIds, key, null);
} else if ('filter' in change) {
// TODO(dimond): implement existence filter parsing with strategy.
assertPresent(change.filter, 'filter');
const filter = change.filter;
assertPresent(filter.targetId, 'filter.targetId');
const { count = 0, unchangedNames } = filter;
const existenceFilter = new ExistenceFilter(count, unchangedNames);
const targetId = filter.targetId;
watchChange = new ExistenceFilterChange(targetId, existenceFilter);
} else {
return fail('Unknown change type ' + JSON.stringify(change));
}
return watchChange;
}
function fromWatchTargetChangeState(
state: ProtoTargetChangeTargetChangeType
): WatchTargetChangeState {
if (state === 'NO_CHANGE') {
return WatchTargetChangeState.NoChange;
} else if (state === 'ADD') {
return WatchTargetChangeState.Added;
} else if (state === 'REMOVE') {
return WatchTargetChangeState.Removed;
} else if (state === 'CURRENT') {
return WatchTargetChangeState.Current;
} else if (state === 'RESET') {
return WatchTargetChangeState.Reset;
} else {
return fail('Got unexpected TargetChange.state: ' + state);
}
}
export function versionFromListenResponse(
change: ProtoListenResponse
): SnapshotVersion {
// We have only reached a consistent snapshot for the entire stream if there
// is a read_time set and it applies to all targets (i.e. the list of
// targets is empty). The backend is guaranteed to send such responses.
if (!('targetChange' in change)) {
return SnapshotVersion.min();
}
const targetChange = change.targetChange!;
if (targetChange.targetIds && targetChange.targetIds.length) {
return SnapshotVersion.min();
}
if (!targetChange.readTime) {
return SnapshotVersion.min();
}
return fromVersion(targetChange.readTime);
}
export function toMutation(
serializer: JsonProtoSerializer,
mutation: Mutation
): ProtoWrite {
let result: ProtoWrite;
if (mutation instanceof SetMutation) {
result = {
update: toMutationDocument(serializer, mutation.key, mutation.value)
};
} else if (mutation instanceof DeleteMutation) {
result = { delete: toName(serializer, mutation.key) };
} else if (mutation instanceof PatchMutation) {
result = {
update: toMutationDocument(serializer, mutation.key, mutation.data),
updateMask: toDocumentMask(mutation.fieldMask)
};
} else if (mutation instanceof VerifyMutation) {
result = {
verify: toName(serializer, mutation.key)
};
} else {
return fail('Unknown mutation type ' + mutation.type);
}
if (mutation.fieldTransforms.length > 0) {
result.updateTransforms = mutation.fieldTransforms.map(transform =>
toFieldTransform(serializer, transform)
);
}
if (!mutation.precondition.isNone) {
result.currentDocument = toPrecondition(serializer, mutation.precondition);
}
return result;
}
export function fromMutation(
serializer: JsonProtoSerializer,
proto: ProtoWrite
): Mutation {
const precondition = proto.currentDocument
? fromPrecondition(proto.currentDocument)
: Precondition.none();
const fieldTransforms = proto.updateTransforms
? proto.updateTransforms.map(transform =>
fromFieldTransform(serializer, transform)
)
: [];
if (proto.update) {
assertPresent(proto.update.name, 'name');
const key = fromName(serializer, proto.update.name);
const value = new ObjectValue({
mapValue: { fields: proto.update.fields }
});
if (proto.updateMask) {
const fieldMask = fromDocumentMask(proto.updateMask);
return new PatchMutation(
key,
value,
fieldMask,
precondition,
fieldTransforms
);
} else {
return new SetMutation(key, value, precondition, fieldTransforms);
}
} else if (proto.delete) {
const key = fromName(serializer, proto.delete);
return new DeleteMutation(key, precondition);
} else if (proto.verify) {
const key = fromName(serializer, proto.verify);
return new VerifyMutation(key, precondition);
} else {
return fail('unknown mutation proto: ' + JSON.stringify(proto));
}
}
function toPrecondition(
serializer: JsonProtoSerializer,
precondition: Precondition
): ProtoPrecondition {
debugAssert(!precondition.isNone, "Can't serialize an empty precondition");
if (precondition.updateTime !== undefined) {
return {
updateTime: toVersion(serializer, precondition.updateTime)
};
} else if (precondition.exists !== undefined) {
return { exists: precondition.exists };
} else {
return fail('Unknown precondition');
}
}
function fromPrecondition(precondition: ProtoPrecondition): Precondition {
if (precondition.updateTime !== undefined) {
return Precondition.updateTime(fromVersion(precondition.updateTime));
} else if (precondition.exists !== undefined) {
return Precondition.exists(precondition.exists);
} else {
return Precondition.none();
}
}
function fromWriteResult(
proto: ProtoWriteResult,
commitTime: ProtoTimestamp
): MutationResult {
// NOTE: Deletes don't have an updateTime.
let version = proto.updateTime
? fromVersion(proto.updateTime)
: fromVersion(commitTime);
if (version.isEqual(SnapshotVersion.min())) {
// The Firestore Emulator currently returns an update time of 0 for
// deletes of non-existing documents (rather than null). This breaks the
// test "get deleted doc while offline with source=cache" as NoDocuments
// with version 0 are filtered by IndexedDb's RemoteDocumentCache.
// TODO(#2149): Remove this when Emulator is fixed
version = fromVersion(commitTime);
}
return new MutationResult(version, proto.transformResults || []);
}
export function fromWriteResults(
protos: ProtoWriteResult[] | undefined,
commitTime?: ProtoTimestamp
): MutationResult[] {
if (protos && protos.length > 0) {
hardAssert(
commitTime !== undefined,
'Received a write result without a commit time'
);
return protos.map(proto => fromWriteResult(proto, commitTime));
} else {
return [];
}
}
function toFieldTransform(
serializer: JsonProtoSerializer,
fieldTransform: FieldTransform
): ProtoFieldTransform {
const transform = fieldTransform.transform;
if (transform instanceof ServerTimestampTransform) {
return {
fieldPath: fieldTransform.field.canonicalString(),
setToServerValue: 'REQUEST_TIME'
};
} else if (transform instanceof ArrayUnionTransformOperation) {
return {
fieldPath: fieldTransform.field.canonicalString(),
appendMissingElements: {
values: transform.elements
}
};
} else if (transform instanceof ArrayRemoveTransformOperation) {
return {
fieldPath: fieldTransform.field.canonicalString(),
removeAllFromArray: {
values: transform.elements
}
};
} else if (transform instanceof NumericIncrementTransformOperation) {
return {
fieldPath: fieldTransform.field.canonicalString(),
increment: transform.operand
};
} else {
throw fail('Unknown transform: ' + fieldTransform.transform);
}
}
function fromFieldTransform(
serializer: JsonProtoSerializer,
proto: ProtoFieldTransform
): FieldTransform {
let transform: TransformOperation | null = null;
if ('setToServerValue' in proto) {
hardAssert(
proto.setToServerValue === 'REQUEST_TIME',
'Unknown server value transform proto: ' + JSON.stringify(proto)
);
transform = new ServerTimestampTransform();
} else if ('appendMissingElements' in proto) {
const values = proto.appendMissingElements!.values || [];
transform = new ArrayUnionTransformOperation(values);
} else if ('removeAllFromArray' in proto) {
const values = proto.removeAllFromArray!.values || [];
transform = new ArrayRemoveTransformOperation(values);
} else if ('increment' in proto) {
transform = new NumericIncrementTransformOperation(
serializer,
proto.increment!
);
} else {
fail('Unknown transform proto: ' + JSON.stringify(proto));
}
const fieldPath = FieldPath.fromServerFormat(proto.fieldPath!);
return new FieldTransform(fieldPath, transform!);
}
export function toDocumentsTarget(
serializer: JsonProtoSerializer,
target: Target
): ProtoDocumentsTarget {
return { documents: [toQueryPath(serializer, target.path)] };
}
export function fromDocumentsTarget(
documentsTarget: ProtoDocumentsTarget
): Target {
const count = documentsTarget.documents!.length;
hardAssert(
count === 1,
'DocumentsTarget contained other than 1 document: ' + count
);
const name = documentsTarget.documents![0];
return queryToTarget(newQueryForPath(fromQueryPath(name)));
}
export function toQueryTarget(
serializer: JsonProtoSerializer,
target: Target
): ProtoQueryTarget {
// Dissect the path into parent, collectionId, and optional key filter.
const result: ProtoQueryTarget = { structuredQuery: {} };
const path = target.path;
if (target.collectionGroup !== null) {
debugAssert(
path.length % 2 === 0,
'Collection Group queries should be within a document path or root.'
);
result.parent = toQueryPath(serializer, path);
result.structuredQuery!.from = [
{
collectionId: target.collectionGroup,
allDescendants: true
}
];
} else {
debugAssert(
path.length % 2 !== 0,
'Document queries with filters are not supported.'
);
result.parent = toQueryPath(serializer, path.popLast());
result.structuredQuery!.from = [{ collectionId: path.lastSegment() }];
}
const where = toFilters(target.filters);
if (where) {
result.structuredQuery!.where = where;
}
const orderBy = toOrder(target.orderBy);
if (orderBy) {
result.structuredQuery!.orderBy = orderBy;
}
const limit = toInt32Proto(serializer, target.limit);
if (limit !== null) {
result.structuredQuery!.limit = limit;
}
if (target.startAt) {
result.structuredQuery!.startAt = toStartAtCursor(target.startAt);
}
if (target.endAt) {
result.structuredQuery!.endAt = toEndAtCursor(target.endAt);
}
return result;
}
export function toRunAggregationQueryRequest(
serializer: JsonProtoSerializer,
target: Target,
aggregates: Aggregate[]
): ProtoRunAggregationQueryRequest {
const queryTarget = toQueryTarget(serializer, target);
const aggregations: ProtoAggregation[] = [];
aggregates.forEach(aggregate => {
if (aggregate.aggregateType === 'count') {
aggregations.push({
alias: aggregate.alias.canonicalString(),
count: {}
});
} else if (aggregate.aggregateType === 'avg') {
aggregations.push({
alias: aggregate.alias.canonicalString(),
avg: {
field: toFieldPathReference(aggregate.fieldPath!)
}
});
} else if (aggregate.aggregateType === 'sum') {
aggregations.push({
alias: aggregate.alias.canonicalString(),
sum: {
field: toFieldPathReference(aggregate.fieldPath!)
}
});
}
});
return {
structuredAggregationQuery: {
aggregations,
structuredQuery: queryTarget.structuredQuery
},
parent: queryTarget.parent
};
}
export function convertQueryTargetToQuery(target: ProtoQueryTarget): Query {
let path = fromQueryPath(target.parent!);
const query = target.structuredQuery!;
const fromCount = query.from ? query.from.length : 0;
let collectionGroup: string | null = null;
if (fromCount > 0) {
hardAssert(
fromCount === 1,
'StructuredQuery.from with more than one collection is not supported.'
);
const from = query.from![0];
if (from.allDescendants) {
collectionGroup = from.collectionId!;
} else {
path = path.child(from.collectionId!);
}
}
let filterBy: Filter[] = [];
if (query.where) {
filterBy = fromFilters(query.where);
}
let orderBy: OrderBy[] = [];
if (query.orderBy) {
orderBy = fromOrder(query.orderBy);
}
let limit: number | null = null;
if (query.limit) {
limit = fromInt32Proto(query.limit);
}
let startAt: Bound | null = null;
if (query.startAt) {
startAt = fromStartAtCursor(query.startAt);
}
let endAt: Bound | null = null;
if (query.endAt) {
endAt = fromEndAtCursor(query.endAt);
}
return newQuery(
path,
collectionGroup,
orderBy,
filterBy,
limit,
LimitType.First,
startAt,
endAt
);