-
-
Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathmormot.net.openapi.pas
3093 lines (2863 loc) · 94.6 KB
/
mormot.net.openapi.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
/// OpenAPI Client Code Generation
// - this unit is a part of the Open Source Synopse mORMot framework 2,
// licensed under a MPL/GPL/LGPL three license - see LICENSE.md
unit mormot.net.openapi;
{
*****************************************************************************
OpenAPI Language-agnostic Interface to HTTP APIs
- OpenAPI Document Wrappers
- FPC/Delphi Pascal Client Code Generation
*****************************************************************************
In Respect to existing OpenAPI wrappers in Delphi (or FPC):
- Use high-level pascal records and dynamic arrays for "object" DTOs
- Use high-level pascal enumerations and sets for "enum" values
- Translate HTTP status error codes into high-level pascal Exceptions
- Recognize similar "properties" or "enum" to reuse the same pascal type
- Support of nested "$ref" for objects, parameters or types
- Support "allOf" attribute, with proper properties inheritance/overloading
- Support "oneOf" attribute, for strings or alternate record types
- Support of "in":"header" and "in":"cookie" parameter attributes
- Fallback to variant pascal type for "oneOf" or "anyOf" JSON values
- Generated source code units are very small and easy to use, read and debug
- Can generate very detailed comment documentation in the unit source code
- Tunable engine, with plenty of generation options (e.g. about verbosity)
- Leverage the mORMot RTTI and JSON kernel for its internal plumbing
- Compatible with FPC and oldest Delphi (7-2009)
- Tested with several Swagger 2 and OpenAPI 2-3 reference content
But still not fully compliant to all existing files: feedback is welcome!
REFERENCE: https://swagger.io/docs/specification
TODO: - operation: "multipart/form-data" in "consumes" and "in":"formdata"
- authentification as in global "securityDefinitions"
}
interface
{$I ..\mormot.defines.inc}
uses
sysutils,
classes,
mormot.core.base,
mormot.core.os,
mormot.core.unicode,
mormot.core.text,
mormot.core.buffers,
mormot.core.datetime,
mormot.core.rtti,
mormot.core.data, // for TRawUtf8List
mormot.core.variants;
{ ************************************ OpenAPI Document Wrappers }
type
/// exception class raised by this Unit
EOpenApi = class(ESynException);
TOpenApiParser = class; // forward declaration
/// define the Swagger (oav2) or OpenAPI 3.x (oav3) schema
TOpenApiVersion = (
oavUnknown,
oav2,
oav3);
/// define the native built-in pascal types
TOpenApiBuiltInType = (
obtVariant,
obtRecord,
obtInteger,
obtInt64,
obtBoolean,
obtEnumerationOrSet,
obtSingle,
obtDouble,
obtDate,
obtDateTime,
obtGuid,
obtRawUtf8,
obtSpiUtf8,
obtString,
obtRawByteString);
/// define the location of an OpenAPI parameter ('"in" field)
TOpenApiParamLocation = (
oplUnsupported,
oplPath,
oplQuery,
oplBody,
oplHeader,
oplCookie,
oplFormData);
/// pointer wrapper to TDocVariantData / variant content of an OpenAPI Schema
POpenApiSchema = ^TOpenApiSchema;
/// a dynamic array of pointers wrapper to OpenAPI Schema definition(s)
POpenApiSchemaDynArray = array of POpenApiSchema;
/// high-level OpenAPI Schema wrapper to TDocVariantData / variant content
{$ifdef USERECORDWITHMETHODS}
TOpenApiSchema = record
{$else}
TOpenApiSchema = object
{$endif USERECORDWITHMETHODS}
private
function GetPropertyByName(const aName: RawUtf8): POpenApiSchema;
public
/// transtype the POpenApiSchema pointer into a TDocVariantData content
Data: TDocVariantData;
// access to the OpenAPI Schema information
function _Type: RawUtf8;
function _Format: RawUtf8;
function Required: PDocVariantData;
function Enum: PDocVariantData;
function Nullable: boolean;
function Description: RawUtf8;
function ExampleAsText: RawUtf8;
function PatternAsText: RawUtf8;
function Reference: RawUtf8;
function AllOf: POpenApiSchemaDynArray;
function Items: POpenApiSchema;
function ItemsOrNil: POpenApiSchema;
function Properties: PDocVariantData;
property _Property[const aName: RawUtf8]: POpenApiSchema
read GetPropertyByName;
// high-level OpenAPI Schema Helpers
function IsArray: boolean;
function IsObject: boolean;
function IsNamedEnum: boolean;
function BuiltInType(Parser: TOpenApiParser): TOpenApiBuiltInType;
function HasDescription: boolean;
function HasItems: boolean;
function HasProperties: boolean;
function HasExample: boolean;
function HasPattern: boolean;
end;
/// high-level OpenAPI Schema wrapper to TDocVariantData / variant content
{$ifdef USERECORDWITHMETHODS}
TOpenApiResponse = record
{$else}
TOpenApiResponse = object
{$endif USERECORDWITHMETHODS}
public
/// transtype the POpenApiResponse pointer into a TDocVariantData content
Data: TDocVariantData;
// access to the OpenAPI Response information
function Description: RawUtf8;
function Schema(Parser: TOpenApiParser): POpenApiSchema;
end;
/// pointer wrapper to TDocVariantData / variant content of an OpenAPI Response
POpenApiResponse = ^TOpenApiResponse;
/// pointer wrapper to TDocVariantData / variant content of an OpenAPI RequestBody
// - share the very same fields as TOpenApiResponse
POpenApiRequestBody = {$ifdef USERECORDWITHMETHODS} type {$endif}POpenApiResponse;
/// high-level OpenAPI Parameter wrapper to TDocVariantData / variant content
{$ifdef USERECORDWITHMETHODS}
TOpenApiParameter = record
{$else}
TOpenApiParameter = object
{$endif USERECORDWITHMETHODS}
public
/// transtype the POpenApiParameter pointer into a TDocVariantData content
Data: TDocVariantData;
// access to the OpenAPI Parameter information
function Name: RawUtf8;
function Description: RawUtf8;
function AsPascalName: RawUtf8;
function _In: RawUtf8;
function Location: TOpenApiParamLocation;
function AllowEmptyValues: boolean;
function Default: PVariant;
function Required: boolean;
function Schema(Parser: TOpenApiParser): POpenApiSchema;
end;
/// pointer wrapper to TDocVariantData / variant content of an OpenAPI Parameter
POpenApiParameter = ^TOpenApiParameter;
/// high-level OpenAPI Parameter wrapper to TDocVariantData / variant content
{$ifdef USERECORDWITHMETHODS}
TOpenApiParameters = record
{$else}
TOpenApiParameters = object
{$endif USERECORDWITHMETHODS}
private
function GetParameterByIndex(aIndex: integer): POpenApiParameter;
{$ifdef HASINLINE} inline; {$endif}
public
/// transtype the POpenApiParameters pointer into a TDocVariantData content
Data: TDocVariantData;
// access to the OpenAPI Parameters information
function Count: integer;
property Parameter[aIndex: integer]: POpenApiParameter
read GetParameterByIndex;
end;
/// pointer wrapper to TDocVariantData / variant content of an OpenAPI Parameters
POpenApiParameters = ^TOpenApiParameters;
/// high-level OpenAPI Operation wrapper to TDocVariantData / variant content
{$ifdef USERECORDWITHMETHODS}
TOpenApiOperation = record
{$else}
TOpenApiOperation = object
{$endif USERECORDWITHMETHODS}
private
function GetResponseForStatusCode(aStatusCode: integer): POpenApiResponse;
public
/// transtype the POpenApiOperation pointer into a TDocVariantData content
Data: TDocVariantData;
// access to the OpenAPI Operation information
function Id: RawUtf8;
function Summary: RawUtf8;
function Description: RawUtf8;
function Tags: TRawUtf8DynArray;
function Deprecated: boolean;
function Parameters: POpenApiParameters;
function RequestBody(Parser: TOpenApiParser): POpenApiRequestBody;
function Responses: PDocVariantData;
function ProducesJson: boolean;
property Response[aStatusCode: integer]: POpenApiResponse
read GetResponseForStatusCode;
end;
/// pointer wrapper to TDocVariantData / variant content of an OpenAPI Operation
POpenApiOperation = ^TOpenApiOperation;
/// high-level OpenAPI Path Item wrapper to TDocVariantData / variant content
{$ifdef USERECORDWITHMETHODS}
TOpenApiPathItem = record
{$else}
TOpenApiPathItem = object
{$endif USERECORDWITHMETHODS}
private
function GetOperationByMethod(aMethod: TUriMethod): POpenApiOperation;
public
/// transtype the POpenApiPathItem pointer into a TDocVariantData content
Data: TDocVariantData;
// access to the OpenAPI Path Item information
function Summary: RawUtf8;
function Description: RawUtf8;
function Parameters: POpenApiParameters;
property Method[aMethod: TUriMethod]: POpenApiOperation
read GetOperationByMethod;
end;
/// pointer wrapper to TDocVariantData / variant content of an OpenAPI Path Item
POpenApiPathItem = ^TOpenApiPathItem;
/// high-level OpenAPI Tag wrapper to TDocVariantData / variant content
{$ifdef USERECORDWITHMETHODS}
TOpenApiTag = record
{$else}
TOpenApiTag = object
{$endif USERECORDWITHMETHODS}
public
/// transtype the POpenApiTag pointer into a TDocVariantData content
Data: TDocVariantData;
// access to the OpenAPI Tag information
function Description: RawUtf8;
function Name: RawUtf8;
end;
/// pointer wrapper to TDocVariantData / variant content of an OpenAPI Tag
POpenApiTag = ^TOpenApiTag;
/// high-level OpenAPI Specations wrapper to TDocVariantData / variant content
{$ifdef USERECORDWITHMETHODS}
TOpenApiSpecs = record
{$else}
TOpenApiSpecs = object
{$endif USERECORDWITHMETHODS}
private
function GetPathItemByName(const aPath: RawUtf8): POpenApiPathItem;
public
/// transtype the POpenApiSpecs pointer into a TDocVariantData content
Data: TDocVariantData;
// access to the main OpenAPI Specifications information
function Info: PDocVariantData;
function BasePath: RawUtf8;
function Paths: PDocVariantData;
function Tags: PDocVariantData;
function Version: RawUtf8;
function VersionEnum: TOpenApiVersion;
property Path[const aPath: RawUtf8]: POpenApiPathItem
read GetPathItemByName;
function Components: PDocVariantData;
function Schemas(aVersion: TOpenApiVersion): PDocVariantData;
end;
/// pointer wrapper to TDocVariantData / variant content of OpenAPI Specs
POpenApiSpecs = ^TOpenApiSpecs;
{ ************************************ FPC/Delphi Pascal Client Code Generation }
TPascalCustomType = class;
TPascalParameter = class;
TPascalRecord = class;
TPascalRecordDynArray = array of TPascalRecord;
/// define any Pascal type, as basic type of custom type
TPascalType = class
protected
fParser: TOpenApiParser;
fBuiltinSchema: POpenApiSchema;
fBuiltInTypeName: RawUtf8;
fCustomType: TPascalCustomType;
fBuiltInType: TOpenApiBuiltInType;
fIsArray, fNoConst: boolean;
function GetSchema: POpenApiSchema;
procedure SetArray(AValue: boolean);
public
constructor CreateBuiltin(aParser: TOpenApiParser;
aBuiltInType: TOpenApiBuiltInType; aSchema: POpenApiSchema = nil;
aIsArray: boolean = false); overload;
constructor CreateCustom(aCustomType: TPascalCustomType); overload;
// TODO: Handle RecordArrayType in RTTI definition
function ToPascalName(AsFinalType: boolean = true;
NoRecordArrayTypes: boolean = false): RawUtf8;
function ToFormatUtf8Arg(const VarName: RawUtf8): RawUtf8;
function ToDefaultParameterValue(aParam: TPascalParameter): RawUtf8;
function IsBuiltin: boolean;
function IsEnum: boolean;
function IsRecord: boolean;
{$ifdef HASINLINE} inline; {$endif}
property IsArray: boolean
read fIsArray write SetArray;
property CustomType: TPascalCustomType
read fCustomType;
property BuiltInType: TOpenApiBuiltInType
read fBuiltInType;
property Schema: POpenApiSchema
read GetSchema;
end;
TPascalTypeObjArray = array of TPascalType;
/// abstract parent class to define Pascal grammar items
TPascalAbstract = class
protected
fName: RawUtf8;
fPascalName: RawUtf8;
fParser: TOpenApiParser;
fSchema: POpenApiSchema;
public
property Name: RawUtf8
read fName;
property PascalName: RawUtf8
read fPascalName;
property Schema: POpenApiSchema
read fSchema;
end;
/// define a Pascal property
TPascalProperty = class(TPascalAbstract)
private
fType: TPascalType;
fTypeOwned: boolean;
public
constructor CreateFromSchema(aParser: TOpenApiParser; const aName: RawUtf8;
aSchema: POpenApiSchema);
constructor CreateFrom(aAnother: TPascalProperty);
constructor CreateBuiltin(aParser: TOpenApiParser; const aName, aPascalName: RawUtf8;
aBuiltInType: TOpenApiBuiltInType);
procedure ConvertToVariant;
destructor Destroy; override;
property PropType: TPascalType
read fType;
end;
/// abstract parent class holder for complex types
TPascalCustomType = class(TPascalAbstract)
protected
fFromRef: RawUtf8;
fRequiresArrayDefinition: boolean;
public
constructor Create(aParser: TOpenApiParser);
procedure ToTypeDefinition(W: TTextWriter); virtual; abstract;
function ToArrayTypeName(AsFinalType: boolean = true): RawUtf8; virtual;
function ToArrayTypeDefinition: RawUtf8; virtual;
end;
/// define a Pascal data structure, as a packed record with RTTI
TPascalRecord = class(TPascalCustomType)
private
fProperties: TRawUtf8List; // Objects are owned TPascalProperty
fRttiTextRepresentation: RawUtf8;
fTypes: set of TOpenApiBuiltInType;
fNeedsDummyField, fIsVoidVariant: boolean;
procedure ResolveDependencies(var all, pending: TPascalRecordDynArray);
public
constructor Create(aParser: TOpenApiParser; const SchemaName: RawUtf8;
Schema: POpenApiSchema = nil);
destructor Destroy; override;
procedure CopyProperties(aDest: TPascalRecord);
procedure ToTypeDefinition(W: TTextWriter); override;
function ToRttiTextRepresentation: RawUtf8;
function ToRttiRegisterDefinitions: RawUtf8;
property Properties: TRawUtf8List
read fProperties;
end;
/// define a Pascal enumeration type
TPascalEnum = class(TPascalCustomType)
private
fPrefix, fConstTextArrayName: RawUtf8;
fChoices: TDocVariantData;
fDynArrayEnum: boolean; // true if fChoices.Count > ENUM_MAX = 64
public
constructor Create(aParser: TOpenApiParser; const aName: RawUtf8;
aSchema: POpenApiSchema);
procedure ToTypeDefinition(W: TTextWriter); override;
procedure ToRegisterCustom(W: TTextWriter);
function ToArrayTypeName(AsFinalType: boolean = true): RawUtf8; override;
procedure ToConstTextArray(W: TTextWriter);
property Prefix: RawUtf8
read fPrefix;
end;
/// define a custom Pascal EJsonClient type (used for 4xx responses)
TPascalException = class(TPascalCustomType)
private
fResponse: POpenApiResponse;
fErrorType: TPascalType;
fErrorTypeName: RawUtf8;
fErrorCode: RawUtf8;
public
constructor Create(aParser: TOpenApiParser; const aCode: RawUtf8;
aResponse: POpenApiResponse = nil);
destructor Destroy; override;
procedure ToTypeDefinition(W: TTextWriter); override;
procedure Body(W: TTextWriter);
property Response: POpenApiResponse
read fResponse;
property ErrorType: TPascalType
read fErrorType;
property ErrorCode: RawUtf8
read fErrorCode;
end;
/// define a Pascal method parameter matching an OpenAPI operation parameter
TPascalParameter = class(TPascalAbstract)
protected
fParameter: POpenApiParameter;
fLocation: TOpenApiParamLocation;
fType: TPascalType;
fRequired: boolean;
fDefault: PVariant;
public
constructor Create(aParser: TOpenApiParser; aParam: POpenApiParameter);
destructor Destroy; override;
property Parameter: POpenApiParameter
read fParameter;
property Location: TOpenApiParamLocation
read fLocation;
property ParamType: TPascalType
read fType;
end;
TPascalParameterDynArray = array of TPascalParameter;
/// define a Pascal method matching an OpenAPI operation
TPascalOperation = class
private
fParser: TOpenApiParser;
fOperationId: RawUtf8;
fFunctionName: RawUtf8;
fMethod, fPath: RawUtf8;
fPathItem: POpenApiPathItem;
fOperation: POpenApiOperation;
fRequestBody: POpenApiRequestBody;
fRequestBodySchema: POpenApiSchema;
fPayloadParameterType: TPascalType;
fSuccessResponseType: TPascalType;
fSuccessResponseCode: integer;
fOnErrorIndex: integer;
fParameters: TPascalParameterDynArray;
public
constructor Create(aParser: TOpenApiParser; const aMethod, aPath: RawUtf8;
aPathItem: POpenApiPathItem; aOperation: POpenApiOperation);
destructor Destroy; override;
procedure ResolveResponseTypes;
procedure Documentation(W: TTextWriter);
procedure Declaration(W: TTextWriter; const ClassName: RawUtf8;
InImplementation: boolean);
procedure Body(W: TTextWriter; const ClassName, BasePath: RawUtf8);
property Operation: POpenApiOperation
read fOperation;
property OperationId: RawUtf8
read fOperationId;
property FunctionName: RawUtf8
read fFunctionName;
property Parameters: TPascalParameterDynArray
read fParameters;
end;
TPascalOperationDynArray = array of TPascalOperation;
TPascalOperationsByTag = record
TagName: RawUtf8;
Tag: POpenApiTag;
Operations: TPascalOperationDynArray;
end;
TPascalOperationsByTagDynArray = array of TPascalOperationsByTag;
/// allow to customize TOpenApiParser process
// - opoNoEnum disables any pascal enumeration type generation
// - opoNoDateTime disables any pascal TDate/TDateTime type generation
// - opoDtoNoDescription generates no Description comment for the DTOs
// - opoDtoNoRefFrom generates no 'from #/....' comment for the DTOs
// - opoDtoNoExample generates no 'Example:' comment for the DTOs
// - opoDtoNoPattern generates no 'Pattern:' comment for the DTOs
// - opoClientExcludeDeprecated removes any operation marked as deprecated
// - opoClientNoDescription generates only the minimal comments for the client
// - opoClientNoException won't generate any exception, and fallback to EJsonClient
// - opoClientOnlySummary will reduce the verbosity of operation comments
// - opoGenerateSingleApiUnit will let GenerateClient return a single
// {name}.api unit, containing both the needed DTOs and the client class
// - opoGenerateStringType will generate plain string types instead of RawUtf8
// - opoGenerateOldDelphiCompatible will generate a void/dummy managed field for
// Delphi 7/2007/2009 compatibility and avoid 'T... has no type info' errors,
// and also properly support Unicode or unfinished/nested record type definitions
// - see e.g. OPENAPI_CONCISE for a single unit, simple and undocumented output
TOpenApiParserOption = (
opoNoEnum,
opoNoDateTime,
opoDtoNoDescription,
opoDtoNoRefFrom,
opoDtoNoExample,
opoDtoNoPattern,
opoClientExcludeDeprecated,
opoClientNoDescription,
opoClientNoException,
opoClientOnlySummary,
opoGenerateSingleApiUnit,
opoGenerateStringType,
opoGenerateOldDelphiCompatible);
TOpenApiParserOptions = set of TOpenApiParserOption;
/// the main OpenAPI parser and pascal code generator class
TOpenApiParser = class
protected
fLineEnd: RawUtf8;
fLineIndent: RawUtf8;
fSpecs: TOpenApiSpecs;
fInfo: PDocVariantData;
fSchemas: PDocVariantData;
fRecords: TRawUtf8List; // objects are owned TPascalRecord
fEnums: TRawUtf8List; // objects are owned TPascalEnum
fExceptions: TRawUtf8List; // objects are owned TPascalException
fErrorHandler: TRawUtf8DynArray;
fOperations: TPascalOperationDynArray;
fName: RawUtf8;
fTitle, fGeneratedBy, fGeneratedByLine: RawUtf8;
fVersion: TOpenApiVersion;
fOptions: TOpenApiParserOptions;
fEnumCounter, fDtoCounter: integer;
fDtoUnitName, fClientUnitName, fClientClassName: RawUtf8;
fOrderedRecords: TPascalRecordDynArray;
fEnumPrefix: TRawUtf8DynArray;
function ParseRecordDefinition(const aDefinitionName: RawUtf8;
aSchema: POpenApiSchema; aTemporary: boolean = false): TPascalRecord;
procedure ParsePath(const aPath: RawUtf8; aPathItem: POpenApiPathItem);
function NewPascalTypeFromSchema(aSchema: POpenApiSchema;
aSchemaName: RawUtf8 = ''): TPascalType;
function GetRecord(aRecordName: RawUtf8; aSchema: POpenApiSchema;
NameIsReference: boolean = false): TPascalRecord;
function GetOrderedRecords: TPascalRecordDynArray;
function GetOperationsByTag: TPascalOperationsByTagDynArray;
function GetSchemaByName(const aName: RawUtf8): POpenApiSchema;
function GetRef(aRef: RawUtf8): pointer;
procedure Description(W: TTextWriter; const Described: RawUtf8);
procedure Comment(W: TTextWriter; const Args: array of const;
const Desc: RawUtf8 = '');
procedure Code(W: TTextWriter; var Line: RawUtf8; const Args: array of const);
// main internal parsing function
procedure ParseSpecs;
// main internal code generation methods
procedure GenerateDtoInterface(w: TTextWriter);
procedure GenerateDtoImplementation(w: TTextWriter);
public
/// initialize this parser instance
// - aName is a short identifier used for naming the units and types
constructor Create(const aName: RawUtf8; aOptions: TOpenApiParserOptions = []);
/// finalize this parser instance
destructor Destroy; override;
/// parse a JSON Swagger/OpenAPI file content
procedure ParseFile(const aJsonFile: TFileName);
/// parse a JSON Swagger/OpenAPI content
procedure ParseJson(const aJson: RawUtf8);
/// parse a Swagger/OpenAPI content tree from an existing TDocVariant
procedure ParseData(const aSpecs: TDocVariantData);
/// clear all internal information of this parser instance
procedure Clear;
/// generate the DTO unit content
function GenerateDtoUnit: RawUtf8;
/// generate the main Client unit content
// - including all DTOs if the opoGenerateSingleApiUnit option is defined
function GenerateClientUnit: RawUtf8;
/// generate the DTO and main Client unit .pas files in a given folder
// - no DTO unit is written if the opoGenerateSingleApiUnit option is defined
procedure ExportToDirectory(const DirectoryName: TFileName = '');
/// allow to customize the code generation
property Options: TOpenApiParserOptions
read fOptions write fOptions;
/// the line feed content to be used for code generation
property LineEnd: RawUtf8
read fLineEnd;
/// short identifier of a few chars, used as prefix for code generation
// - used e.g. for computing the default unit names
// - also used when generating TDto### and TEnum### types, to avoid any
// conflict at RTTI level between the names, especially if several OpenAPI
// generated units do coexist in the project
property Name: RawUtf8
read fName write fName;
/// the unit identifier name used for the DTO unit, without the '.pas' extension
// - default value will be lowercase '{name}.dto'
property DtoUnitName: RawUtf8
read fDtoUnitName write fDtoUnitName;
/// the unit identifier name used for the Client unit, without the '.pas' extension
// - default value will be lowercase '{name}.client' or '{name}.api' if
// the opoGenerateSingleApiUnit option is defined
property ClientUnitName: RawUtf8
read fClientUnitName write fClientUnitName;
/// the class identifier name, by default 'T{Name}Client'
property ClientClassName: RawUtf8
read fClientClassName write fClientClassName;
/// main storage of the whole OpenAPI specifications tree
property Specs: TOpenApiSpecs
read fSpecs;
/// the layout version of the parsed specifications
property Version: TOpenApiVersion
read fVersion;
/// the main title, as stored in the parsed specifications
property Title: RawUtf8
read fTitle;
/// resolve a given Schema by its name
property Schema[const aName: RawUtf8]: POpenApiSchema
read GetSchemaByName;
/// list all operations (aka Pascal methods) stored in the parsed specifications
property Operations: TPascalOperationDynArray
read fOperations;
end;
const
/// TOpenApiParser options to generate a single, simple and undocumented unit
// - if the default two-units setup with full documentation seems too verbose
OPENAPI_CONCISE = [
opoGenerateSingleApiUnit,
opoDtoNoDescription,
opoClientNoDescription];
function ToText(t: TOpenApiBuiltInType): PShortString; overload;
implementation
{ ************************************ OpenAPI Document Wrappers }
{ TOpenApiSchema }
function TOpenApiSchema.AllOf: POpenApiSchemaDynArray;
var
all: PDocVariantData;
i: PtrInt;
begin
result := nil;
if not Data.GetAsArray('allOf', all) then
exit;
SetLength(result, all^.Count);
for i := 0 to high(result) do
result[i] := pointer(_Safe(all^.Values[i]));
end;
function TOpenApiSchema.Items: POpenApiSchema;
begin
if not IsArray then
EOpenApi.RaiseUtf8('TOpenApiSchema.Items on a non array: %', [_Type]);
if not Data.GetAsObject('items', PDocVariantData(result)) then
result := nil;
end;
function TOpenApiSchema.ItemsOrNil: POpenApiSchema;
begin
if not IsArray or
not Data.GetAsObject('items', PDocVariantData(result)) then
result := nil;
end;
function TOpenApiSchema.HasItems: boolean;
begin
result := IsArray and
Data.Exists('items');
end;
function TOpenApiSchema.HasProperties: boolean;
begin
result := Data.Exists('properties');
end;
function TOpenApiSchema.Properties: PDocVariantData;
begin
if not Data.GetAsObject('properties', result) then
result := nil;
end;
function TOpenApiSchema.GetPropertyByName(const aName: RawUtf8): POpenApiSchema;
begin
if not Properties^.GetAsObject(aName, PDocVariantData(result)) then
result := nil;
end;
function TOpenApiSchema.Reference: RawUtf8;
begin
result := Data.U['$ref']
end;
function TOpenApiSchema.Nullable: boolean;
begin
result := Data.B['nullable'];
end;
function TOpenApiSchema.Required: PDocVariantData;
begin
result := Data.A['required']
end;
function TOpenApiSchema.Description: RawUtf8;
begin
result := TrimU(Data.U['description']);
end;
function TOpenApiSchema.HasDescription: boolean;
begin
result := Description <> '';
end;
function TOpenApiSchema.Enum: PDocVariantData;
begin
if not Data.GetAsArray('enum', result) then
result := nil;
end;
function TOpenApiSchema.ExampleAsText: RawUtf8;
begin
result := VariantSaveJson(Data.Value['example']);
end;
function TOpenApiSchema.PatternAsText: RawUtf8;
begin
result := VariantSaveJson(Data.Value['pattern']);
end;
function TOpenApiSchema.HasExample: boolean;
begin
result := Data.Exists('example');
end;
function TOpenApiSchema.HasPattern: boolean;
begin
result := Data.Exists('pattern');
end;
function TOpenApiSchema._Format: RawUtf8;
begin
result := Data.U['format'];
end;
function TOpenApiSchema._Type: RawUtf8;
begin
result := Data.U['type'];
end;
function TOpenApiSchema.IsArray: boolean;
begin
result := _Type = 'array';
end;
function TOpenApiSchema.IsObject: boolean;
begin
result := _Type = 'object';
end;
function TOpenApiSchema.IsNamedEnum: boolean;
begin
result := (Enum <> nil) and
(_Format <> '');
end;
function TOpenApiSchema.BuiltInType(Parser: TOpenApiParser): TOpenApiBuiltInType;
var
t, f, ref: RawUtf8;
oo: PDocVariantData;
s: POpenApiSchema;
r: TPascalRecord;
i: PtrInt;
begin
result := obtVariant; // fallback type: anything up to TDocVariantData
t := _Type;
if t = '' then
begin
if Data.GetAsArray('oneOf', oo) then
begin
s := @oo^.Values[0];
result := s^.BuiltInType(Parser);
if result = obtVariant then
begin
if (s^.Reference = '') or
(Description <> '') then
exit;
for i := 0 to oo^.Count - 1 do
begin
ref := POpenApiSchema(@oo^.Values[i])^.Reference;
if ref = '' then
continue;
r := Parser.GetRecord(ref, nil, {isref=}true);
if r <> nil then
Append(t, r.PascalName, ' ');
end;
if t <> '' then
Data.U['description'] := Make(['From the JSON of ', t]);
end
else
for i := 1 to oo^.Count - 1 do
if POpenApiSchema(@oo^.Values[i])^.BuiltInType(Parser) <> result then
begin
result := obtVariant; // all simple "type" should match
exit;
end;
end;
end
else
begin
f := _Format;
if t = 'integer' then
if f = 'int64' then
result := obtInt64
else
result := obtInteger
else if t = 'number' then
if f = 'float' then
result := obtSingle
else
result := obtDouble
else if t = 'boolean' then
result := obtBoolean
else if t = 'string' then
begin
result := obtRawUtf8;
if f <> '' then
if f = 'uuid' then
result := obtGuid
else if f = 'binary' then
result := obtRawByteString
else if f = 'password' then
result := obtSpiUtf8
else if not (opoNoDateTime in Parser.Options) then
if f = 'date' then
result := obtDate
else if f = 'date-time' then
result := obtDateTime;
end;
end;
if opoGenerateStringType in Parser.Options then
if result in [obtRawUtf8, obtSpiUtf8] then
result := obtString;
end;
{ TOpenApiResponse }
function TOpenApiResponse.Description: RawUtf8;
begin
result := TrimU(Data.U['description']);
end;
function TOpenApiResponse.Schema(Parser: TOpenApiParser): POpenApiSchema;
var
ref, n: RawUtf8;
c, o: PDocVariantData;
i: PtrInt;
begin
if @self = nil then
result := nil
else if Data.GetAsRawUtf8('$ref', ref) then
result := POpenApiResponse(Parser.GetRef(ref)).Schema(Parser)
else if Parser.Version = oav2 then
result := POpenApiSchema(Data.O['schema'])
else
begin
// we only support application/json (and some variations) here
result := nil;
c := Data.O['content'];
for i := 0 to c.Count - 1 do
if result = nil then
begin
n := c.Names[i];
if IsContentTypeJsonU(n) or
(n = '*/*') or
IdemPropNameU(n, 'application/jwt') then // exists in the wild :(
if _SafeObject(c.Values[i], o) then
result := POpenApiSchema(o.O['schema']);
end;
if result = nil then // allow fallback e.g. to text/plain schema:type:string
for i := 0 to c.Count - 1 do
if result = nil then
if IdemPChar(pointer(c.Names[i]), 'TEXT/PLAIN') and
_SafeObject(c.Values[i], o) then
result := POpenApiSchema(o.O['schema']);
end;
if (result <> nil) and
(result^.Data.Count = 0) then
result := nil; // no such schema
end;
{ TOpenApiParameter }
function TOpenApiParameter.AllowEmptyValues: boolean;
begin
result := Data.B['allowEmptyValue'];
end;
function TOpenApiParameter.Description: RawUtf8;
begin
result := TrimU(Data.U['description']);
end;
function TOpenApiParameter.Default: PVariant;
begin
result := Data.GetPVariantByPath('default');
end;
function TOpenApiParameter._In: RawUtf8;
begin
result := Data.U['in'];
end;
function TOpenApiParameter.Location: TOpenApiParamLocation;
var
i: integer;
begin
i := GetEnumNameValue(TypeInfo(TOpenApiParamLocation), _In, {trimlowcase=}true);
result := oplUnsupported;
if i >= 0 then
result := TOpenApiParamLocation(i);
end;
function TOpenApiParameter.Name: RawUtf8;
begin
result := Data.U['name'];
end;
function TOpenApiParameter.Required: boolean;
begin
result := Data.B['required'];
end;
function TOpenApiParameter.Schema(Parser: TOpenApiParser): POpenApiSchema;
begin
if Parser.Version = oav2 then
result := POpenApiSchema(@self)
else if not Data.GetAsObject('schema', PDocVariantData(result)) then
result := nil;
end;
function TOpenApiParameter.AsPascalName: RawUtf8;
begin
result := Name;
if result <> '' then
result := SanitizePascalName(result, {keywordcheck:}true);
end;
{ TOpenApiTag }
function TOpenApiTag.Description: RawUtf8;
begin
if @self = nil then
result := ''
else
result := TrimU(Data.U['description']);
end;
function TOpenApiTag.Name: RawUtf8;
begin
result := Data.U['name'];
end;