-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathFB4D.Document.pas
1854 lines (1740 loc) · 57.3 KB
/
FB4D.Document.pas
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
{******************************************************************************}
{ }
{ Delphi FB4D Library }
{ Copyright (c) 2018-2023 Christoph Schneider }
{ Schneider Infosystems AG, Switzerland }
{ https://github.com/SchneiderInfosystems/FB4D }
{ }
{******************************************************************************}
{ }
{ 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. }
{ }
{******************************************************************************}
unit FB4D.Document;
interface
uses
System.Types, System.Classes, System.JSON, System.SysUtils, System.StrUtils,
System.Rtti, System.TypInfo,
{$IFNDEF LINUX64}
System.Sensors,
{$ENDIF}
FB4D.Interfaces, FB4D.Response, FB4D.Request, FB4D.Helpers;
{$WARN DUPLICATE_CTOR_DTOR OFF}
type
TFirestoreDocument = class(TInterfacedObject, IFirestoreDocument)
private
fJSONObj: TJSONObject;
fCreated, fUpdated: TDateTime;
fDocumentName: string;
fFields: array of record
Name: string;
Obj: TJSONObject;
end;
function FieldIndByName(const FieldName: string): integer;
function ConvertRefPath(const Reference: string): string;
function ArrayToFSArr(R: TRTTIType; V: TValue;
const FName: string): TFirestoreArr;
function DynArrToFSArr(R: TRTTIType; V: TValue;
const FName: string): TFirestoreArr;
function EnumToI64(V: TValue; const FName: string): Int64;
function FloatToObj(R: TRTTIType; V: TValue): TJSONObject;
function MapToFSMap(DAT: TRttiRecordType; V: TValue): TFirestoreMap;
function SetToStr(V: TValue): string;
procedure LoadObjectFromDoc;
function AnsiCharToVal(TypeInfo: PTypeInfo; const s: string): TValue;
function AnsiStringToVal(TypeInfo: PTypeInfo; const s: string): TValue;
function ArrayToVal(F: TRTTIField; Arr: TJSONObjects): TValue;
function CharToVal(TypeInfo: PTypeInfo; const s: string): TValue;
function DynArrayToVal(F: TRTTIField; Arr: TJSONObjects): TValue;
function EnumToVal(TypeInfo: PTypeInfo; I: Int64): TValue;
function FloatToVal(RType: TRTTIType; Obj: TJSONObject): TValue;
function RecordToVal(DAT: TRttiRecordType; const FName: string;
Map: TJSONObject): TValue;
function SetToVal(TypeInfo: PTypeInfo; const s: string): TValue;
function WideStringToVal(TypeInfo: PTypeInfo; const s: string): TValue;
public
class function CreateCursor(const ProjectID: string): IFirestoreDocument;
class function GetDocFullPath(
const ProjectID: string;
const Database: string = cDefaultDatabaseID;
DocumentPath: TRequestResourceParam = []): TRequestResourceParam; overload;
class function GetDocFullPath(DocumentPath: TRequestResourceParam;
const ProjectID: string;
const Database: string = cDefaultDatabaseID): string; overload;
constructor Create(DocumentPath: TRequestResourceParam;
const ProjectID: string; const Database: string = cDefaultDatabaseID);
overload;
constructor Create(DocumentPath: TRequestResourceParam;
Firestore: IFirestoreDatabase); overload;
constructor CreateFromJSONObj(Response: IFirebaseResponse); overload;
constructor CreateFromJSONObj(JSONObj: TJSONObject); overload;
destructor Destroy; override;
function DocumentName(FullPath: boolean): string;
function DocumentFullPath: TRequestResourceParam;
function DocumentPathWithinDatabase: TRequestResourceParam;
function CreateTime(TimeZone: TTimeZone = tzUTC): TDateTime;
function UpdateTime(TimeZone: TTimeZone = tzUTC): TDatetime;
function CountFields: integer;
function FieldName(Ind: integer): string;
function FieldByName(const FieldName: string): TJSONObject;
function FieldValue(Ind: integer): TJSONObject;
function FieldType(Ind: integer): TFirestoreFieldType;
function FieldTypeByName(const FieldName: string): TFirestoreFieldType;
function AllFields: TStringDynArray;
function GetValue(Ind: integer): TJSONValue; overload;
function GetValue(const FieldName: string): TJSONValue; overload;
function GetStringValue(const FieldName: string): string;
function GetStringValueDef(const FieldName, Default: string): string;
function GetIntegerValue(const FieldName: string): integer;
function GetIntegerValueDef(const FieldName: string;
Default: integer): integer;
function GetInt64Value(const FieldName: string): Int64;
function GetInt64ValueDef(const FieldName: string;
Default: Int64): Int64;
function GetDoubleValue(const FieldName: string): double;
function GetDoubleValueDef(const FieldName: string;
Default: double): double;
function GetTimeStampValue(const FieldName: string;
TimeZone: TTimeZone = tzUTC): TDateTime;
function GetTimeStampValueDef(const FieldName: string;
Default: TDateTime; TimeZone: TTimeZone = tzUTC): TDateTime;
function GetBoolValue(const FieldName: string): boolean;
function GetBoolValueDef(const FieldName: string;
Default: boolean): boolean;
function GetGeoPoint(const FieldName: string): TLocationCoord2D;
function GetReference(const FieldName: string): string;
function GetReferenceDef(const FieldName, Default: string): string;
function GetBytes(const FieldName: string): TBytes;
function GetArraySize(const FieldName: string): integer;
function GetArrayType(const FieldName: string;
Index: integer): TFirestoreFieldType;
function GetArrayItem(const FieldName: string; Index: integer): TJSONPair;
function GetArrayValue(const FieldName: string; Index: integer): TJSONValue;
function GetArrayValues(const FieldName: string): TJSONObjects;
function GetArrayMapValues(const FieldName: string): TJSONObjects;
function GetArrayStringValues(const FieldName: string): TStringDynArray;
function GetMapSize(const FieldName: string): integer;
function GetMapType(const FieldName: string;
Index: integer): TFirestoreFieldType;
function GetMapSubFieldName(const FieldName: string; Index: integer): string;
function GetMapValue(const FieldName: string; Index: integer): TJSONObject;
overload;
function GetMapValue(const FieldName, SubFieldName: string): TJSONObject;
overload;
function GetMapValues(const FieldName: string): TJSONObjects;
procedure AddOrUpdate(Field: TJSONPair); overload;
procedure AddOrUpdate(const FieldName: string; Val: TJSONValue); overload;
function AddOrUpdateField(Field: TJSONPair): IFirestoreDocument; overload;
function AddOrUpdateField(const FieldName: string;
Val: TJSONValue): IFirestoreDocument;
overload;
function AsJSON: TJSONObject;
function Clone: IFirestoreDocument;
class function GetFieldType(const FieldType: string): TFirestoreFieldType;
class function IsCompositeType(FieldType: TFirestoreFieldType): boolean;
{ Object to Document Mapper }
constructor LoadObjectFromDocument(Doc: IFirestoreDocument);
function SaveObjectToDocument: IFirestoreDocument;
end;
TFirestoreDocuments = class(TInterfacedObject, IFirestoreDocuments,
IEnumerable<IFirestoreDocument>, IEnumerable)
private
fDocumentList: array of IFirestoreDocument;
fServerTimeStampUTC: TDatetime;
fPageToken: string;
fSkippedResults: integer;
protected
function GetGenericEnumerator: IEnumerator<IFirestoreDocument>;
function GetEnumerator: IEnumerator;
function IFirestoreDocuments.GetEnumerator = GetGenericEnumerator;
function IEnumerable<IFirestoreDocument>.GetEnumerator =
GetGenericEnumerator;
public
constructor CreateFromJSONDocumentsObj(Response: IFirebaseResponse);
class function IsJSONDocumentsObj(Response: IFirebaseResponse): boolean;
constructor CreateFromJSONArr(Response: IFirebaseResponse);
destructor Destroy; override;
procedure AddFromJSONDocumentsObj(Response: IFirebaseResponse);
function Count: integer;
function Document(Ind: integer): IFirestoreDocument;
function ServerTimeStamp(TimeZone: TTimeZone): TDateTime;
function SkippedResults: integer;
function MorePagesToLoad: boolean;
function PageToken: string;
procedure AddPageTokenToNextQuery(Query: TQueryParams);
end;
TFirestoreDocsEnumerator = class(TInterfacedObject,
IEnumerator<IFirestoreDocument>, IEnumerator)
private
fDocs: TFirestoreDocuments;
fCursor: integer;
protected
protected
function GetCurrent: TObject;
function GenericGetCurrent: IFirestoreDocument;
function IEnumerator<IFirestoreDocument>.GetCurrent = GenericGetCurrent;
public
constructor Create(Docs: TFirestoreDocuments);
function MoveNext: Boolean;
procedure Reset;
end;
implementation
uses
System.Generics.Collections, System.NetEncoding;
resourcestring
rsInvalidDocNotOneNode = 'Invalid document - not one node only';
rsInvalidDocNode = 'Invalid document node: %s';
rsNotObj = 'not an object: ';
rsInvalidDocArr = 'Invalid document - not an array: %s';
rsInvalidDocumentPath =
'Invalid document path "%s", expected "projects/*/database/*/documents"';
rsDocIndexOutOfBound = 'Index out of bound for document list';
rsInvalidDocNodeCountLess3 = 'Invalid document - node count less 3';
rsJSONFieldNameMissing = 'JSON field name missing';
rsJSONFieldCreateTimeMissing = 'JSON field createTime missing';
rsJSONFieldUpdateTimeMissing = 'JSON field updateTime missing';
rsFieldIsNotJSONObj = 'Field %d is not a JSON object as expected';
rsFieldIndexOutOfBound = 'Index out of bound for field list';
rsFieldNotContainJSONObj = 'Field does not contain a JSONObject';
rsFieldNotContainTypeValPair = 'Field does not contain type-value pair';
rsFieldNoFound = 'Field %s not found';
rsArrFieldNotJSONObj = 'Arrayfield[%d] does not contain a JSONObject';
rsArrFieldNotTypeValue = 'Arrayfield[%d] does not contain type-value pair';
rsArrFieldNoMap = 'Arrayfield[%d] does not contain a map';
rsArrIndexOutOfBound = 'Array index out of bound for array field';
rsMapIndexOutOfBound = 'Map index out of bound for array field';
rsInvalidMapField = 'Field %s is not a map field';
{ TFirestoreDocuments }
constructor TFirestoreDocuments.CreateFromJSONArr(Response: IFirebaseResponse);
var
JSONArr: TJSONArray;
Obj: TJSONObject;
c: integer;
begin
inherited Create;
fSkippedResults := 0;
fPageToken := '';
JSONArr := Response.GetContentAsJSONArr;
try
SetLength(fDocumentList, 0);
if JSONArr.Count < 1 then
raise EFirestoreDocument.Create(rsInvalidDocNotOneNode);
for c := 0 to JSONArr.Count - 1 do
begin
Obj := JSONArr.Items[c] as TJSONObject;
if (JSONArr.Count >= 1) and
(Obj.Pairs[0].JsonString.Value = 'readTime') then
begin
// Empty [{'#$A' "readTime": "2018-06-21T08:08:50.445723Z"'#$A'}'#$A']
SetLength(fDocumentList, 0);
if (JSONArr.Count >= 2) and
(Obj.Pairs[1].JsonString.Value = 'skippedResults') then
fSkippedResults := (Obj.Pairs[1].JsonValue as TJSONNumber).AsInt;
end
else if Obj.Pairs[0].JsonString.Value <> 'document' then
raise EFirestoreDocument.CreateFmt(rsInvalidDocNode,
[Obj.Pairs[0].JsonString.ToString])
else if not(Obj.Pairs[0].JsonValue is TJSONObject) then
raise EFirestoreDocument.CreateFmt(rsInvalidDocNode,
[rsNotObj + Obj.ToString])
else begin
SetLength(fDocumentList, length(fDocumentList) + 1);
fDocumentList[length(fDocumentList) - 1] :=
TFirestoreDocument.CreateFromJSONObj(
Obj.Pairs[0].JsonValue as TJSONObject);
end;
end;
finally
JSONArr.Free;
end;
fServerTimeStampUTC := Response.GetServerTime(tzUTC);
end;
constructor TFirestoreDocuments.CreateFromJSONDocumentsObj(
Response: IFirebaseResponse);
var
c: integer;
JSONObj: TJSONObject;
JSONArr: TJSONArray;
begin
fSkippedResults := 0;
JSONObj := Response.GetContentAsJSONObj;
try
if JSONObj.Count < 1 then
SetLength(fDocumentList, 0)
else if JSONObj.Pairs[0].JsonString.Value = 'documents' then
begin
if not(JSONObj.Pairs[0].JsonValue is TJSONArray) then
raise EFirestoreDocument.CreateFmt(rsInvalidDocArr, [JSONObj.ToString]);
JSONArr := JSONObj.Pairs[0].JsonValue as TJSONArray;
SetLength(fDocumentList, JSONArr.Count);
for c := 0 to JSONArr.Count - 1 do
fDocumentList[c] := TFirestoreDocument.CreateFromJSONObj(
JSONArr.Items[c] as TJSONObject);
end else begin
SetLength(fDocumentList, 1);
fDocumentList[0] := TFirestoreDocument.CreateFromJSONObj(JSONObj);
end;
fServerTimeStampUTC := Response.GetServerTime(tzUTC);
if not JSONObj.TryGetValue<string>('nextPageToken', fPageToken) then
fPageToken := '';
finally
JSONObj.Free;
end;
end;
procedure TFirestoreDocuments.AddFromJSONDocumentsObj(
Response: IFirebaseResponse);
var
c, l: integer;
JSONObj: TJSONObject;
JSONArr: TJSONArray;
begin
fSkippedResults := 0;
JSONObj := Response.GetContentAsJSONObj;
try
if JSONObj.Count >= 1 then
begin
l := length(fDocumentList);
if JSONObj.Pairs[0].JsonString.Value = 'documents' then
begin
if not(JSONObj.Pairs[0].JsonValue is TJSONArray) then
raise EFirestoreDocument.CreateFmt(rsInvalidDocArr,
[JSONObj.ToString]);
JSONArr := JSONObj.Pairs[0].JsonValue as TJSONArray;
SetLength(fDocumentList, l + JSONArr.Count);
for c := 0 to JSONArr.Count - 1 do
fDocumentList[l + c] := TFirestoreDocument.CreateFromJSONObj(
JSONArr.Items[c] as TJSONObject);
end else begin
SetLength(fDocumentList, l + 1);
fDocumentList[l] := TFirestoreDocument.CreateFromJSONObj(JSONObj);
end;
end;
fServerTimeStampUTC := Response.GetServerTime(tzUTC);
if not JSONObj.TryGetValue<string>('nextPageToken', fPageToken) then
fPageToken := '';
finally
JSONObj.Free;
end;
end;
class function TFirestoreDocuments.IsJSONDocumentsObj(
Response: IFirebaseResponse): boolean;
var
JSONObj: TJSONObject;
begin
JSONObj := Response.GetContentAsJSONObj;
try
result := (JSONObj.Count = 1) and
(JSONObj.Pairs[0].JsonString.ToString = '"documents"');
finally
JSONObj.Free;
end;
end;
destructor TFirestoreDocuments.Destroy;
begin
SetLength(fDocumentList, 0);
inherited;
end;
function TFirestoreDocuments.Count: integer;
begin
result := length(fDocumentList);
end;
function TFirestoreDocuments.Document(Ind: integer): IFirestoreDocument;
begin
if (Ind >= 0) and (Ind < Count) then
result := fDocumentList[Ind]
else
raise EFirestoreDocument.Create(rsDocIndexOutOfBound);
end;
function TFirestoreDocuments.ServerTimeStamp(TimeZone: TTimeZone): TDateTime;
const
cInitialDate: double = 0;
begin
case TimeZone of
tzUTC:
result := fServerTimeStampUTC;
tzLocalTime:
result := TFirebaseHelpers.ConvertToLocalDateTime(fServerTimeStampUTC);
else
result := TDateTime(cInitialDate);
end;
end;
function TFirestoreDocuments.SkippedResults: integer;
begin
result := fSkippedResults;
end;
function TFirestoreDocuments.MorePagesToLoad: boolean;
begin
result := not fPageToken.IsEmpty;
end;
function TFirestoreDocuments.PageToken: string;
begin
result := fPageToken;
end;
procedure TFirestoreDocuments.AddPageTokenToNextQuery(Query: TQueryParams);
begin
if MorePagesToLoad then
Query.AddPageToken(fPageToken);
end;
function TFirestoreDocuments.GetEnumerator: IEnumerator;
begin
result := GetGenericEnumerator;
end;
function TFirestoreDocuments.GetGenericEnumerator: IEnumerator<IFirestoreDocument>;
begin
result := TFirestoreDocsEnumerator.Create(self);
end;
{ TFirestoreDocument }
class function TFirestoreDocument.GetDocFullPath(
DocumentPath: TRequestResourceParam; const ProjectID,
Database: string): string;
begin
result := Format(cFirestoreDocumentPath,
[ProjectID, Database, TFirebaseHelpers.EncodeResourceParams(DocumentPath)]);
end;
class function TFirestoreDocument.GetDocFullPath(const ProjectID,
Database: string; DocumentPath: TRequestResourceParam): TRequestResourceParam;
var
c, c0: integer;
begin
result := ['projects', ProjectID, 'databases', Database, 'documents'];
if length(DocumentPath) > 0 then
begin
c0 := length(result);
SetLength(result, c0 + length(DocumentPath));
for c := 0 to length(DocumentPath) - 1 do
result[c0 + c] := DocumentPath[c];
end;
end;
constructor TFirestoreDocument.Create(DocumentPath: TRequestResourceParam;
const ProjectID, Database: string);
begin
inherited Create;
fDocumentName := GetDocFullPath(DocumentPath, ProjectID, Database);
fJSONObj := TJSONObject.Create;
fJSONObj.AddPair('name', fDocumentName);
SetLength(fFields, 0);
end;
constructor TFirestoreDocument.Create(DocumentPath: TRequestResourceParam;
Firestore: IFirestoreDatabase);
begin
Create(DocumentPath, Firestore.ProjectID, Firestore.DatabaseID);
end;
class function TFirestoreDocument.CreateCursor(
const ProjectID: string): IFirestoreDocument;
begin
result := TFirestoreDocument.Create(['CursorDoc'], ProjectID);
end;
constructor TFirestoreDocument.CreateFromJSONObj(JSONObj: TJSONObject);
var
obj: TJSONObject;
c: integer;
begin
inherited Create;
fJSONObj := JSONObj.Clone as TJSONObject;
if fJSONObj.Count < 3 then
raise EFirestoreDocument.Create(rsInvalidDocNodeCountLess3);
if not fJSONObj.TryGetValue('name', fDocumentName) then
raise EStorageObject.Create(rsJSONFieldNameMissing);
if not fJSONObj.TryGetValue('createTime', fCreated) then
raise EStorageObject.Create(rsJSONFieldCreateTimeMissing);
if not fJSONObj.TryGetValue('updateTime', fUpdated) then
raise EStorageObject.Create(rsJSONFieldUpdateTimeMissing);
if fJSONObj.TryGetValue('fields', obj) then
begin
SetLength(fFields, obj.Count);
for c := 0 to CountFields - 1 do
begin
fFields[c].Name := obj.Pairs[c].JsonString.Value;
if not(obj.Pairs[c].JsonValue is TJSONObject) then
raise EStorageObject.CreateFmt(rsFieldIsNotJSONObj, [c]);
fFields[c].Obj := obj.Pairs[c].JsonValue.Clone as TJSONObject;
end;
end else
SetLength(fFields, 0);
end;
constructor TFirestoreDocument.CreateFromJSONObj(Response: IFirebaseResponse);
var
JSONObj: TJSONObject;
begin
JSONObj := Response.GetContentAsJSONObj;
try
CreateFromJSONObj(JSONObj);
finally
JSONObj.Free;
end;
end;
destructor TFirestoreDocument.Destroy;
var
c: integer;
begin
for c := 0 to length(fFields) - 1 do
FreeAndNil(fFields[c].Obj);
SetLength(fFields, 0);
fJSONObj.Free;
inherited;
end;
function TFirestoreDocument.FieldIndByName(const FieldName: string): integer;
var
c: integer;
begin
result := -1;
for c := 0 to CountFields - 1 do
if SameText(fFields[c].Name, FieldName) then
exit(c);
end;
procedure TFirestoreDocument.AddOrUpdate(const FieldName: string;
Val: TJSONValue);
var
FieldsObj: TJSONObject;
Ind: integer;
begin
Assert(Assigned(fJSONObj), 'Missing JSON object in AddOrUpdateField');
if not fJSONObj.TryGetValue('fields', FieldsObj) then
begin
FieldsObj := TJSONObject.Create;
fJSONObj.AddPair('fields', FieldsObj);
end;
Ind := FieldIndByName(FieldName);
if Ind < 0 then
begin
Ind := CountFields;
SetLength(fFields, Ind + 1);
fFields[Ind].Name := FieldName;
end else
FieldsObj.RemovePair(FieldName).free;
FieldsObj.AddPair(FieldName, Val);
fFields[Ind].Obj := Val.Clone as TJSONObject;
end;
function TFirestoreDocument.AddOrUpdateField(const FieldName: string;
Val: TJSONValue): IFirestoreDocument;
begin
AddOrUpdate(FieldName, Val);
result := self;
end;
procedure TFirestoreDocument.AddOrUpdate(Field: TJSONPair);
var
FieldName: string;
FieldsObj: TJSONObject;
Ind: integer;
begin
FieldName := Field.JsonString.Value;
if not fJSONObj.TryGetValue('fields', FieldsObj) then
begin
FieldsObj := TJSONObject.Create;
fJSONObj.AddPair('fields', FieldsObj);
end;
Ind := FieldIndByName(FieldName);
if Ind < 0 then
begin
Ind := CountFields;
SetLength(fFields, Ind + 1);
fFields[Ind].Name := FieldName;
end else
FieldsObj.RemovePair(FieldName).free;
FieldsObj.AddPair(Field);
fFields[Ind].Obj := Field.JsonValue.Clone as TJSONObject;
end;
function TFirestoreDocument.AddOrUpdateField(
Field: TJSONPair): IFirestoreDocument;
begin
AddOrUpdate(Field);
result := self;
end;
function TFirestoreDocument.AsJSON: TJSONObject;
begin
result := fJSONObj;
end;
function TFirestoreDocument.CountFields: integer;
begin
result := length(fFields);
end;
function TFirestoreDocument.DocumentName(FullPath: boolean): string;
begin
result := fDocumentName;
if not FullPath then
result := result.SubString(result.LastDelimiter('/') + 1);
end;
function TFirestoreDocument.DocumentFullPath: TRequestResourceParam;
begin
result := fDocumentName.Split(['/']);
end;
function TFirestoreDocument.DocumentPathWithinDatabase: TRequestResourceParam;
var
RemovedProjAndDB: string;
c, p: integer;
begin
p := 0;
for c := 1 to 5 do
begin
p := pos('/', fDocumentName, p + 1);
if p = 0 then
raise EFirestoreDocument.CreateFmt(rsInvalidDocumentPath, [fDocumentName]);
end;
RemovedProjAndDB := copy(fDocumentName, p + 1);
result := RemovedProjAndDB.Split(['/']);
end;
function TFirestoreDocument.FieldName(Ind: integer): string;
begin
if (Ind < 0 ) or (Ind >= CountFields) then
raise EFirestoreDocument.Create(rsFieldIndexOutOfBound);
result := fFields[Ind].Name;
end;
function TFirestoreDocument.FieldType(Ind: integer): TFirestoreFieldType;
var
Obj: TJSONObject;
begin
if (Ind < 0 ) or (Ind >= CountFields) then
raise EFirestoreDocument.Create(rsFieldIndexOutOfBound);
if not(fFields[Ind].Obj is TJSONObject) then
raise EFirestoreDocument.Create(rsFieldNotContainJSONObj);
Obj := fFields[Ind].Obj as TJSONObject;
if Obj.Count <> 1 then
raise EFirestoreDocument.Create(rsFieldNotContainTypeValPair);
result := GetFieldType(Obj.Pairs[0].JsonString.Value);
end;
function TFirestoreDocument.FieldValue(Ind: integer): TJSONObject;
begin
if (Ind < 0 ) or (Ind >= CountFields) then
raise EFirestoreDocument.Create(rsFieldIndexOutOfBound);
result := fFields[Ind].Obj;
end;
function TFirestoreDocument.FieldTypeByName(
const FieldName: string): TFirestoreFieldType;
var
c: integer;
begin
for c := 0 to CountFields - 1 do
if SameText(fFields[c].Name, FieldName) then
exit(FieldType(c));
raise EFirestoreDocument.CreateFmt(rsFieldNoFound, [FieldName]);
end;
function TFirestoreDocument.AllFields: TStringDynArray;
var
c: integer;
begin
SetLength(result, CountFields);
for c := 0 to CountFields - 1 do
result[c] := fFields[c].Name;
end;
class function TFirestoreDocument.GetFieldType(
const FieldType: string): TFirestoreFieldType;
begin
if SameText(FieldType, 'nullValue') then
result := fftNull
else if SameText(FieldType, 'booleanValue') then
result := fftBoolean
else if SameText(FieldType, 'integerValue') then
result := fftInteger
else if SameText(FieldType, 'doubleValue') then
result := fftDouble
else if SameText(FieldType, 'timestampValue') then
result := fftTimeStamp
else if SameText(FieldType, 'stringValue') then
result := fftString
else if SameText(FieldType, 'bytesValue') then
result := fftBytes
else if SameText(FieldType, 'referenceValue') then
result := fftReference
else if SameText(FieldType, 'geoPointValue') then
result := fftGeoPoint
else if SameText(FieldType, 'arrayValue') then
result := fftArray
else if SameText(FieldType, 'mapValue') then
result := fftMap
else
raise EFirestoreDocument.CreateFmt('Unknown field type %s', [FieldType]);
end;
function TFirestoreDocument.FieldByName(const FieldName: string): TJSONObject;
var
c: integer;
begin
result := nil;
for c := 0 to CountFields - 1 do
if SameText(fFields[c].Name, FieldName) then
exit(fFields[c].Obj);
end;
function TFirestoreDocument.GetValue(Ind: integer): TJSONValue;
var
Obj: TJSONObject;
begin
if Ind >= CountFields then
raise EFirestoreDocument.Create(rsFieldIndexOutOfBound);
if not(fFields[Ind].Obj is TJSONObject) then
raise EFirestoreDocument.Create(rsFieldNotContainJSONObj);
Obj := fFields[Ind].Obj as TJSONObject;
if Obj.Count <> 1 then
raise EFirestoreDocument.Create(rsFieldNotContainTypeValPair);
result := Obj.Pairs[0].JsonValue;
end;
function TFirestoreDocument.GetValue(const FieldName: string): TJSONValue;
var
c: integer;
begin
for c := 0 to CountFields - 1 do
if SameText(fFields[c].Name, FieldName) then
exit(GetValue(c));
raise EFirestoreDocument.CreateFmt(rsFieldNoFound, [FieldName]);
end;
function TFirestoreDocument.GetStringValue(const FieldName: string): string;
var
Val: TJSONValue;
begin
Val := FieldByName(FieldName);
if assigned(Val) then
result := Val.GetValue<string>('stringValue')
else
raise EFirestoreDocument.CreateFmt(rsFieldNoFound, [FieldName]);
end;
function TFirestoreDocument.GetStringValueDef(const FieldName,
Default: string): string;
var
Val: TJSONValue;
begin
Val := FieldByName(FieldName);
if not assigned(Val) then
result := Default
else if not Val.TryGetValue<string>('stringValue', result) then
result := Default;
end;
function TFirestoreDocument.GetIntegerValue(const FieldName: string): integer;
var
Val: TJSONValue;
begin
Val := FieldByName(FieldName);
if assigned(Val) then
result := Val.GetValue<integer>('integerValue')
else
raise EFirestoreDocument.CreateFmt(rsFieldNoFound, [FieldName]);
end;
function TFirestoreDocument.GetIntegerValueDef(const FieldName: string;
Default: integer): integer;
var
Val: TJSONValue;
begin
Val := FieldByName(FieldName);
if not assigned(Val) then
result := Default
else if not Val.TryGetValue<integer>('integerValue', result) then
result := Default;
end;
function TFirestoreDocument.GetInt64Value(const FieldName: string): Int64;
var
Val: TJSONValue;
begin
Val := FieldByName(FieldName);
if assigned(Val) then
result := Val.GetValue<Int64>('integerValue')
else
raise EFirestoreDocument.CreateFmt(rsFieldNoFound, [FieldName]);
end;
function TFirestoreDocument.GetInt64ValueDef(const FieldName: string;
Default: Int64): Int64;
var
Val: TJSONValue;
begin
Val := FieldByName(FieldName);
if not assigned(Val) then
result := Default
else if not Val.TryGetValue<Int64>('integerValue', result) then
result := Default;
end;
function TFirestoreDocument.GetDoubleValue(const FieldName: string): double;
var
Val: TJSONValue;
begin
Val := FieldByName(FieldName);
if assigned(Val) then
result := Val.GetValue<double>('doubleValue')
else
raise EFirestoreDocument.CreateFmt(rsFieldNoFound, [FieldName]);
end;
function TFirestoreDocument.GetDoubleValueDef(const FieldName: string;
Default: double): double;
var
Val: TJSONValue;
begin
Val := FieldByName(FieldName);
if not assigned(Val) then
result := Default
else if not Val.TryGetValue<double>('doubleValue', result) then
result := Default;
end;
function TFirestoreDocument.GetTimeStampValue(const FieldName: string;
TimeZone: TTimeZone): TDateTime;
var
Val: TJSONValue;
begin
Val := FieldByName(FieldName);
if assigned(Val) then
begin
result := Val.GetValue<TDateTime>('timestampValue');
if TimeZone = tzLocalTime then
result := TFirebaseHelpers.ConvertToLocalDateTime(result);
end else
raise EFirestoreDocument.CreateFmt(rsFieldNoFound, [FieldName]);
end;
function TFirestoreDocument.GetTimeStampValueDef(const FieldName: string;
Default: TDateTime; TimeZone: TTimeZone): TDateTime;
var
Val: TJSONValue;
begin
Val := FieldByName(FieldName);
if not assigned(Val) then
result := Default
else if Val.TryGetValue<TDateTime>('timestampValue', result) then
begin
if TimeZone = tzLocalTime then
result := TFirebaseHelpers.ConvertToLocalDateTime(result);
end else
result := Default;
end;
function TFirestoreDocument.GetBoolValue(const FieldName: string): boolean;
var
Val: TJSONValue;
begin
Val := FieldByName(FieldName);
if assigned(Val) then
result := Val.GetValue<boolean>('booleanValue')
else
raise EFirestoreDocument.CreateFmt(rsFieldNoFound, [FieldName]);
end;
function TFirestoreDocument.GetBoolValueDef(const FieldName: string;
Default: boolean): boolean;
var
Val: TJSONValue;
begin
Val := FieldByName(FieldName);
if not assigned(Val) then
result := Default
else if not Val.TryGetValue<boolean>('booleanValue', result) then
result := Default;
end;
function TFirestoreDocument.GetGeoPoint(
const FieldName: string): TLocationCoord2D;
var
Val: TJSONValue;
begin
Val := FieldByName(FieldName).GetValue<TJSONValue>('geoPointValue');
if assigned(Val) then
result := TLocationCoord2D.Create(Val.GetValue<double>('latitude'),
Val.GetValue<double>('longitude'))
else
raise EFirestoreDocument.CreateFmt(rsFieldNoFound, [FieldName]);
end;
function TFirestoreDocument.ConvertRefPath(const Reference: string): string;
begin
result := StringReplace(Reference, '\/', '/', [rfReplaceAll]);
end;
function TFirestoreDocument.GetReference(const FieldName: string): string;
var
Val: TJSONValue;
begin
Val := FieldByName(FieldName);
if assigned(Val) then
result := ConvertRefPath(Val.GetValue<string>('referenceValue'))
else
raise EFirestoreDocument.CreateFmt(rsFieldNoFound, [FieldName]);
end;
function TFirestoreDocument.GetReferenceDef(const FieldName,
Default: string): string;
var
Val: TJSONValue;
begin
Val := FieldByName(FieldName);
if not assigned(Val) then
result := Default
else if Val.TryGetValue<string>('referenceValue', result) then
result := ConvertRefPath(result)
else
result := Default;
end;
function TFirestoreDocument.GetBytes(const FieldName: string): TBytes;
var
Val: TJSONValue;
begin
Val := FieldByName(FieldName);
if assigned(Val) then
result := TNetEncoding.Base64.DecodeStringToBytes(
Val.GetValue<string>('bytesValue'))
else
raise EFirestoreDocument.CreateFmt(rsFieldNoFound, [FieldName]);
end;
function TFirestoreDocument.GetArraySize(const FieldName: string): integer;
var
Val: TJSONValue;
Obj: TJSONObject;
Arr: TJSONArray;
begin
Val := FieldByName(FieldName);
if not assigned(Val) then
exit(0);
Obj := Val.GetValue<TJSONObject>('arrayValue');
if not assigned(Obj) then
exit(0);
Arr := Obj.GetValue('values') as TJSONArray;
if not assigned(Arr) then
exit(0);
result := Arr.Count;
end;
function TFirestoreDocument.GetArrayValues(
const FieldName: string): TJSONObjects;
var
Val: TJSONValue;
Obj: TJSONObject;
Arr: TJSONArray;
c: integer;
begin
Val := FieldByName(FieldName);
if not assigned(Val) then
exit(nil);
Obj := Val.GetValue<TJSONObject>('arrayValue');
if not assigned(Obj) then
exit(nil);
Arr := Obj.GetValue('values') as TJSONArray;
if not assigned(Arr) then
exit(nil);
SetLength(result, Arr.Count);
for c := 0 to Arr.Count - 1 do
begin
if not(Arr.Items[c] is TJSONObject) then
raise EFirestoreDocument.CreateFmt(rsArrFieldNotJSONObj, [c]);
Obj := Arr.Items[c] as TJSONObject;
if Obj.Count <> 1 then
raise EFirestoreDocument.CreateFmt(rsArrFieldNotTypeValue, [c]);
result[c] := Obj;
end;
end;
function TFirestoreDocument.GetArrayMapValues(
const FieldName: string): TJSONObjects;
var
Val: TJSONValue;
Obj: TJSONObject;
Arr: TJSONArray;
c: integer;
FieldType: string;
begin
Val := FieldByName(FieldName);
if not assigned(Val) then