/
TypeScriptFetchClientCodegen.java
1647 lines (1461 loc) · 72.9 KB
/
TypeScriptFetchClientCodegen.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
* Copyright 2018 SmartBear Software
*
* 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
*
* https://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.
*/
package org.openapitools.codegen.languages;
import com.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.parameters.RequestBody;
import io.swagger.v3.oas.models.responses.ApiResponse;
import io.swagger.v3.oas.models.servers.Server;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.features.DocumentationFeature;
import org.openapitools.codegen.meta.features.SecurityFeature;
import org.openapitools.codegen.model.ModelMap;
import org.openapitools.codegen.model.ModelsMap;
import org.openapitools.codegen.model.OperationsMap;
import org.openapitools.codegen.templating.mustache.IndentedLambda;
import org.openapitools.codegen.utils.ModelUtils;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;
import static org.openapitools.codegen.utils.CamelizeOption.LOWERCASE_FIRST_LETTER;
import static org.openapitools.codegen.utils.StringUtils.*;
public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodegen {
public static final String NPM_REPOSITORY = "npmRepository";
public static final String WITH_INTERFACES = "withInterfaces";
public static final String USE_SINGLE_REQUEST_PARAMETER = "useSingleRequestParameter";
public static final String PREFIX_PARAMETER_INTERFACES = "prefixParameterInterfaces";
public static final String WITHOUT_RUNTIME_CHECKS = "withoutRuntimeChecks";
public static final String STRING_ENUMS = "stringEnums";
public static final String STRING_ENUMS_DESC = "Generate string enums instead of objects for enum values.";
public static final String IMPORT_FILE_EXTENSION_SWITCH = "importFileExtension";
public static final String IMPORT_FILE_EXTENSION_SWITCH_DESC = "File extension to use with relative imports. Set it to '.js' or '.mjs' when using [ESM](https://nodejs.org/api/esm.html).";
public static final String FILE_NAMING = "fileNaming";
public static final String KEBAB_CASE = "kebab-case";
public static final String CAMEL_CASE = "camelCase";
public static final String PASCAL_CASE = "PascalCase";
protected String npmRepository = null;
protected String importFileExtension = "";
private boolean useSingleRequestParameter = true;
private boolean prefixParameterInterfaces = false;
protected boolean addedApiIndex = false;
protected boolean addedModelIndex = false;
protected boolean withoutRuntimeChecks = false;
protected boolean stringEnums = false;
protected String fileNaming = PASCAL_CASE;
// "Saga and Record" mode.
public static final String SAGAS_AND_RECORDS = "sagasAndRecords";
public static final String DETECT_PASSTHROUGH_MODELS_WITH_SUFFIX_AND_FIELD = "detectPassthroughModelsWithSuffixAndField";
public static final String INFER_UNIQUE_ID_FROM_NAME_SUFFIX = "inferUniqueIdFromNameSuffix";
public static final String INFER_ENTITY_FROM_UNIQUE_ID_WITH_NAME = "inferEntityFromUniqueIdWithName";
public static final String PACKAGE_AS_SOURCE_ONLY_LIBRARY = "packageAsSourceOnlyLibrary";
private static final String X_IS_UNIQUE_ID = "x-isUniqueId";
private static final String X_ENTITY_ID = "x-entityId";
private static final String X_OPERATION_RETURN_PASSTHROUGH = "x-operationReturnPassthrough";
private static final String X_KEEP_AS_JS_OBJECT = "x-keepAsJSObject";
protected boolean sagasAndRecords = false;
protected String detectPassthroughModelsWithSuffixAndField = null; // Ex: "Response;data"
protected boolean inferUniqueIdFromNameSuffix = false;
protected String inferEntityFromUniqueIdWithName = null;
protected boolean packageAsSourceOnlyLibrary = false;
public TypeScriptFetchClientCodegen() {
super();
modifyFeatureSet(features -> features
.includeDocumentationFeatures(DocumentationFeature.Readme)
.includeSecurityFeatures(SecurityFeature.BearerToken));
// clear import mapping (from default generator) as TS does not use it
// at the moment
importMapping.clear();
outputFolder = "generated-code/typescript-fetch";
embeddedTemplateDir = templateDir = "typescript-fetch";
this.apiTemplateFiles.put("apis.mustache", ".ts");
this.addExtraReservedWords();
supportModelPropertyNaming(CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.camelCase);
this.cliOptions.add(new CliOption(NPM_REPOSITORY, "Use this property to set an url your private npmRepo in the package.json"));
this.cliOptions.add(new CliOption(WITH_INTERFACES, "Setting this property to true will generate interfaces next to the default class implementations.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString()));
this.cliOptions.add(new CliOption(CodegenConstants.USE_SINGLE_REQUEST_PARAMETER, CodegenConstants.USE_SINGLE_REQUEST_PARAMETER_DESC, SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.TRUE.toString()));
this.cliOptions.add(new CliOption(PREFIX_PARAMETER_INTERFACES, "Setting this property to true will generate parameter interface declarations prefixed with API class name to avoid name conflicts.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString()));
this.cliOptions.add(new CliOption(WITHOUT_RUNTIME_CHECKS, "Setting this property to true will remove any runtime checks on the request and response payloads. Payloads will be casted to their expected types.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString()));
this.cliOptions.add(new CliOption(SAGAS_AND_RECORDS, "Setting this property to true will generate additional files for use with redux-saga and immutablejs.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString()));
this.cliOptions.add(new CliOption(STRING_ENUMS, STRING_ENUMS_DESC, SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString()));
this.cliOptions.add(new CliOption(IMPORT_FILE_EXTENSION_SWITCH, IMPORT_FILE_EXTENSION_SWITCH_DESC).defaultValue(""));
this.cliOptions.add(new CliOption(FILE_NAMING, "Naming convention for the output files: 'PascalCase', 'camelCase', 'kebab-case'.").defaultValue(this.fileNaming));
}
@Override
public String toApiFilename(String name) {
return convertUsingFileNamingConvention(super.toApiFilename(name));
}
@Override
public String toModelFilename(String name) {
return convertUsingFileNamingConvention(super.toModelFilename(name));
}
/**
* Converts the original name according to the current <code>fileNaming</code> strategy.
*
* @param originalName the original name to transform
* @return the transformed name
*/
private String convertUsingFileNamingConvention(String originalName) {
String name = originalName;
if (KEBAB_CASE.equals(fileNaming)) {
name = dashize(underscore(name));
} else if (CAMEL_CASE.equals(fileNaming)) {
name = camelize(name, LOWERCASE_FIRST_LETTER);
}
return name;
}
@Override
public String getName() {
return "typescript-fetch";
}
@Override
public String getHelp() {
return "Generates a TypeScript client library using Fetch API (beta).";
}
public String getNpmRepository() {
return npmRepository;
}
public void setNpmRepository(String npmRepository) {
this.npmRepository = npmRepository;
}
public String getImportFileExtension() {
return importFileExtension;
}
public void setImportFileExtension(String importFileExtension) {
this.importFileExtension = importFileExtension;
}
public Boolean getWithoutRuntimeChecks() {
return withoutRuntimeChecks;
}
public void setWithoutRuntimeChecks(Boolean withoutRuntimeChecks) {
this.withoutRuntimeChecks = withoutRuntimeChecks;
}
public Boolean getStringEnums() {
return this.stringEnums;
}
public void setStringEnums(Boolean stringEnums) {
this.stringEnums = stringEnums;
}
/**
* Set the file naming type.
*
* @param fileNaming the file naming to use
*/
public void setFileNaming(String fileNaming) {
if (PASCAL_CASE.equals(fileNaming) || CAMEL_CASE.equals(fileNaming) || KEBAB_CASE.equals(fileNaming)) {
this.fileNaming = fileNaming;
} else {
throw new IllegalArgumentException("Invalid file naming '" +
fileNaming + "'. Must be 'PascalCase', 'camelCase' or 'kebab-case'");
}
}
public Boolean getSagasAndRecords() {
return sagasAndRecords;
}
public void setSagasAndRecords(Boolean sagasAndRecords) {
this.sagasAndRecords = sagasAndRecords;
}
public String getPassthroughSuffix() {
return detectPassthroughModelsWithSuffixAndField != null ? detectPassthroughModelsWithSuffixAndField.split("\\.")[0] : null;
}
public String getPassthroughField() {
return detectPassthroughModelsWithSuffixAndField != null ? detectPassthroughModelsWithSuffixAndField.split("\\.")[1] : null;
}
public String getDetectPassthroughModelsWithSuffixAndField() {
return detectPassthroughModelsWithSuffixAndField;
}
public void setDetectPassthroughModelsWithSuffixAndField(String detectPassthroughModelsWithSuffixAndField) {
this.detectPassthroughModelsWithSuffixAndField = detectPassthroughModelsWithSuffixAndField;
}
public boolean getInferUniqueIdFromNameSuffix() {
return inferUniqueIdFromNameSuffix;
}
public void setInferUniqueIdFromNameSuffix(boolean inferUniqueIdFromNameSuffix) {
this.inferUniqueIdFromNameSuffix = inferUniqueIdFromNameSuffix;
}
public String getInferEntityFromUniqueIdWithName() {
return inferEntityFromUniqueIdWithName;
}
public void setInferEntityFromUniqueIdWithName(String inferEntityFromUniqueIdWithName) {
this.inferEntityFromUniqueIdWithName = inferEntityFromUniqueIdWithName;
}
public boolean getPackageAsSourceOnlyLibrary() {
return packageAsSourceOnlyLibrary;
}
public void setPackageAsSourceOnlyLibrary(boolean packageAsSourceOnlyLibrary) {
this.packageAsSourceOnlyLibrary = packageAsSourceOnlyLibrary;
}
public boolean isUniqueIdAccordingToNameSuffix(String name) {
if (name == null) {
return false;
}
return "id".equals(name) ||
"ids".equals(name) ||
(name.length() >= 3 && name.endsWith("Id")) ||
(name.length() >= 4 && name.endsWith("Ids"));
}
@Override
public void processOpts() {
super.processOpts();
additionalProperties.put("isOriginalModelPropertyNaming", getModelPropertyNaming() == CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.original);
additionalProperties.put("modelPropertyNaming", getModelPropertyNaming().name());
String sourceDir = "";
if (additionalProperties.containsKey(NPM_NAME)) {
sourceDir = "src" + File.separator;
}
this.apiPackage = sourceDir + "apis";
this.modelPackage = sourceDir + "models";
supportingFiles.add(new SupportingFile("index.mustache", sourceDir, "index.ts"));
supportingFiles.add(new SupportingFile("runtime.mustache", sourceDir, "runtime.ts"));
if (additionalProperties.containsKey(IMPORT_FILE_EXTENSION_SWITCH)) {
this.setImportFileExtension(additionalProperties.get(IMPORT_FILE_EXTENSION_SWITCH).toString());
}
writePropertyBack(IMPORT_FILE_EXTENSION_SWITCH, getImportFileExtension());
if (additionalProperties.containsKey(CodegenConstants.USE_SINGLE_REQUEST_PARAMETER)) {
this.setUseSingleRequestParameter(convertPropertyToBoolean(CodegenConstants.USE_SINGLE_REQUEST_PARAMETER));
}
writePropertyBack(CodegenConstants.USE_SINGLE_REQUEST_PARAMETER, getUseSingleRequestParameter());
if (additionalProperties.containsKey(PREFIX_PARAMETER_INTERFACES)) {
this.setPrefixParameterInterfaces(convertPropertyToBoolean(PREFIX_PARAMETER_INTERFACES));
}
writePropertyBack(PREFIX_PARAMETER_INTERFACES, getPrefixParameterInterfaces());
if (additionalProperties.containsKey(NPM_NAME)) {
addNpmPackageGeneration();
}
if (additionalProperties.containsKey(WITHOUT_RUNTIME_CHECKS)) {
this.setWithoutRuntimeChecks(convertPropertyToBoolean(WITHOUT_RUNTIME_CHECKS));
}
if (additionalProperties.containsKey(STRING_ENUMS)) {
this.setStringEnums(convertPropertyToBoolean(STRING_ENUMS));
}
if (additionalProperties.containsKey(FILE_NAMING)) {
this.setFileNaming(additionalProperties.get(FILE_NAMING).toString());
}
if (!withoutRuntimeChecks) {
this.modelTemplateFiles.put("models.mustache", ".ts");
typeMapping.put("date", "Date");
typeMapping.put("DateTime", "Date");
}
if (additionalProperties.containsKey(SAGAS_AND_RECORDS)) {
this.setSagasAndRecords(convertPropertyToBoolean(SAGAS_AND_RECORDS));
if (this.getSagasAndRecords()) {
apiTemplateFiles.put("sagas.mustache", "Sagas.ts");
modelTemplateFiles.put("records.mustache", "Record.ts");
supportingFiles.add(new SupportingFile("runtimeSagasAndRecords.mustache", sourceDir, "runtimeSagasAndRecords.ts"));
supportingFiles.add(new SupportingFile("ApiEntitiesRecord.mustache", sourceDir, "ApiEntitiesRecord.ts"));
supportingFiles.add(new SupportingFile("ApiEntitiesReducer.mustache", sourceDir, "ApiEntitiesReducer.ts"));
supportingFiles.add(new SupportingFile("ApiEntitiesSelectors.mustache", sourceDir, "ApiEntitiesSelectors.ts"));
if (additionalProperties.containsKey(DETECT_PASSTHROUGH_MODELS_WITH_SUFFIX_AND_FIELD)) {
this.setDetectPassthroughModelsWithSuffixAndField((String) additionalProperties.get(DETECT_PASSTHROUGH_MODELS_WITH_SUFFIX_AND_FIELD));
}
if (additionalProperties.containsKey(INFER_UNIQUE_ID_FROM_NAME_SUFFIX)) {
this.setInferUniqueIdFromNameSuffix(convertPropertyToBoolean(INFER_UNIQUE_ID_FROM_NAME_SUFFIX));
}
if (additionalProperties.containsKey(INFER_ENTITY_FROM_UNIQUE_ID_WITH_NAME)) {
this.setInferEntityFromUniqueIdWithName((String) additionalProperties.get(INFER_ENTITY_FROM_UNIQUE_ID_WITH_NAME));
}
if (additionalProperties.containsKey(PACKAGE_AS_SOURCE_ONLY_LIBRARY)) {
this.setPackageAsSourceOnlyLibrary(convertPropertyToBoolean(PACKAGE_AS_SOURCE_ONLY_LIBRARY));
}
this.addExtraReservedWordsForSagasAndRecords();
if (this.getPackageAsSourceOnlyLibrary()) {
supportingFiles.add(new SupportingFile("sourceLibraryIndex.mustache", "", "index.ts"));
}
}
}
}
@Override
public String toEnumDefaultValue(String value, String datatype) {
if (this.getSagasAndRecords()) {
return datatype + "." + value;
}
return super.toEnumDefaultValue(value, datatype);
}
@Override
protected String getEnumDefaultValue(String defaultValue, String dataType) {
if (this.getSagasAndRecords()) {
return defaultValue;
}
return super.getEnumDefaultValue(defaultValue, dataType);
}
@Override
protected ImmutableMap.Builder<String, Mustache.Lambda> addMustacheLambdas() {
ImmutableMap.Builder<String, Mustache.Lambda> lambdas = super.addMustacheLambdas();
lambdas.put("indented_star_1", new IndentedLambda(1, " ", "* ", false, false));
lambdas.put("indented_star_4", new IndentedLambda(5, " ", "* ", false, false));
return lambdas;
}
@Override
public String getTypeDeclaration(Schema p) {
if (ModelUtils.isFileSchema(p)) {
return "Blob";
} else if (ModelUtils.isBinarySchema(p)) {
return "Blob";
}
return super.getTypeDeclaration(p);
}
@Override
protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, Schema schema) {
codegenModel.additionalPropertiesType = getTypeDeclaration(ModelUtils.getAdditionalProperties(schema));
addImport(codegenModel, codegenModel.additionalPropertiesType);
}
@Override
public ModelsMap postProcessModels(ModelsMap objs) {
List<ModelMap> models = postProcessModelsEnum(objs).getModels();
// process enum and custom properties in models
for (ModelMap mo : models) {
ExtendedCodegenModel cm = (ExtendedCodegenModel) mo.getModel();
cm.imports = new TreeSet<>(cm.imports);
this.processCodeGenModel(cm);
}
// Add supporting file only if we plan to generate files in /models
if (!objs.isEmpty() && !addedModelIndex) {
addedModelIndex = true;
supportingFiles.add(new SupportingFile("models.index.mustache", modelPackage().replace('.', File.separatorChar), "index.ts"));
}
return objs;
}
@Override
public void postProcessParameter(CodegenParameter parameter) {
super.postProcessParameter(parameter);
if (parameter.isFormParam && parameter.isArray && "binary".equals(parameter.dataFormat)) {
parameter.isCollectionFormatMulti = true;
}
}
@Override
public Map<String, ModelsMap> postProcessAllModels(Map<String, ModelsMap> objs) {
List<ExtendedCodegenModel> allModels = new ArrayList<>();
List<String> entityModelClassnames = new ArrayList<>();
Map<String, ModelsMap> result = super.postProcessAllModels(objs);
for (ModelsMap entry : result.values()) {
for (ModelMap model : entry.getModels()) {
ExtendedCodegenModel codegenModel = (ExtendedCodegenModel) model.getModel();
model.put("hasImports", codegenModel.imports.size() > 0);
model.put("tsImports", toTsImports(codegenModel, parseImports(codegenModel)));
allModels.add(codegenModel);
if (codegenModel.isEntity) {
entityModelClassnames.add(codegenModel.classname);
}
}
}
for (ExtendedCodegenModel rootModel : allModels) {
for (String curImport : rootModel.imports) {
boolean isModelImport = false;
for (ExtendedCodegenModel model : allModels) {
if (model.classname.equals(curImport) && !model.isEnum) {
isModelImport = true;
break;
}
}
if (isModelImport) {
rootModel.modelImports.add(curImport);
}
}
for (CodegenProperty cpVar : rootModel.vars) {
ExtendedCodegenProperty var = (ExtendedCodegenProperty) cpVar;
if (var.isModel && entityModelClassnames.indexOf(var.dataType) != -1) {
var.isEntity = true;
} else if (var.isArray && var.items.isModel && entityModelClassnames.indexOf(var.items.dataType) != -1) {
((ExtendedCodegenProperty) var.items).isEntity = true;
}
}
}
return result;
}
/**
* Parse imports
*/
private Set<String> parseImports(CodegenModel cm) {
Set<String> newImports = new HashSet<>();
if (cm.imports.size() > 0) {
for (String name : cm.imports) {
if (name.indexOf(" | ") >= 0) {
String[] parts = name.split(" \\| ");
Collections.addAll(newImports, parts);
} else {
newImports.add(name);
}
}
}
return newImports;
}
private List<Map<String, String>> toTsImports(CodegenModel cm, Set<String> imports) {
List<Map<String, String>> tsImports = new ArrayList<>();
for (String im : imports) {
if (!im.equals(cm.classname)) {
HashMap<String, String> tsImport = new HashMap<>();
// TVG: This is used as class name in the import statements of the model file
tsImport.put("classname", im);
tsImport.put("filename", toModelFilename(im));
tsImports.add(tsImport);
}
}
return tsImports;
}
private void autoSetDefaultValueForProperty(ExtendedCodegenProperty var) {
if (var.isArray || var.isModel) {
var.defaultValue = var.dataTypeAlternate + "()";
} else if (var.isUniqueId) {
var.defaultValue = "\"-1\"";
} else if (var.isEnum) {
var.defaultValue = "'" + var._enum.get(0) + "'";
updateCodegenPropertyEnum(var);
} else if (var.dataType.equalsIgnoreCase("string")) {
var.defaultValue = "\"\"";
} else if (var.dataType.equalsIgnoreCase("number")) {
var.defaultValue = "0";
} else if (var.dataType.equalsIgnoreCase("boolean")) {
var.defaultValue = "false";
} else {
if (var.allowableValues != null && var.allowableValues.get("enumVars") instanceof ArrayList && ((ArrayList) var.allowableValues.get("enumVars")).get(0) instanceof HashMap) {
var.defaultValue = var.dataTypeAlternate + "." + ((HashMap<String, String>) ((ArrayList) var.allowableValues.get("enumVars")).get(0)).get("name");
}
}
}
private void addNpmPackageGeneration() {
if (additionalProperties.containsKey(NPM_REPOSITORY)) {
this.setNpmRepository(additionalProperties.get(NPM_REPOSITORY).toString());
}
//Files for building our lib
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("package.mustache", "", "package.json"));
supportingFiles.add(new SupportingFile("tsconfig.mustache", "", "tsconfig.json"));
// in case ECMAScript 6 is supported add another tsconfig for an ESM (ECMAScript Module)
if (supportsES6) {
supportingFiles.add(new SupportingFile("tsconfig.esm.mustache", "", "tsconfig.esm.json"));
}
supportingFiles.add(new SupportingFile("npmignore.mustache", "", ".npmignore"));
supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore"));
}
@Override
public List<CodegenParameter> fromRequestBodyToFormParameters(RequestBody body, Set<String> imports) {
List<CodegenParameter> superParams = super.fromRequestBodyToFormParameters(body, imports);
List<CodegenParameter> extendedParams = new ArrayList<CodegenParameter>();
for (CodegenParameter cp : superParams) {
extendedParams.add(new ExtendedCodegenParameter(cp));
}
return extendedParams;
}
@Override
public ExtendedCodegenParameter fromParameter(Parameter parameter, Set<String> imports) {
CodegenParameter cp = super.fromParameter(parameter, imports);
return new ExtendedCodegenParameter(cp);
}
@Override
public CodegenParameter fromFormProperty(String name, Schema propertySchema, Set<String> imports) {
CodegenParameter cp = super.fromFormProperty(name, propertySchema, imports);
return new ExtendedCodegenParameter(cp);
}
@Override
public CodegenParameter fromRequestBody(RequestBody body, Set<String> imports, String bodyParameterName) {
CodegenParameter cp = super.fromRequestBody(body, imports, bodyParameterName);
return new ExtendedCodegenParameter(cp);
}
@Override
public ExtendedCodegenProperty fromProperty(String name, Schema p, boolean required) {
CodegenProperty cp = super.fromProperty(name, p, required);
return new ExtendedCodegenProperty(cp);
}
@Override
public ExtendedCodegenModel fromModel(String name, Schema model) {
CodegenModel cm = super.fromModel(name, model);
return new ExtendedCodegenModel(cm);
}
@Override
public ExtendedCodegenOperation fromOperation(String path, String httpMethod, Operation operation, List<Server> servers) {
CodegenOperation superOp = super.fromOperation(path, httpMethod, operation, servers);
ExtendedCodegenOperation op = new ExtendedCodegenOperation(superOp);
if (this.getSagasAndRecords()) {
ApiResponse methodResponse = findMethodResponse(operation.getResponses());
if (methodResponse != null) {
Map<String, Schema> schemas = ModelUtils.getSchemas(this.openAPI);
Schema schema = null;
if (schemas != null) {
schema = schemas.get(op.returnBaseType);
}
ExtendedCodegenModel cm = null;
if (schema != null) {
cm = fromModel(op.returnBaseType, schema);
Object returnPassthrough = cm.vendorExtensions.get(X_OPERATION_RETURN_PASSTHROUGH);
if (returnPassthrough instanceof String) {
if (((String) returnPassthrough).isEmpty()) {
op.hasReturnPassthroughVoid = true;
op.returnPassthrough = null;
} else {
boolean foundMatch = false;
for (CodegenProperty var : cm.vars) {
if (var.name.equals(returnPassthrough)) {
foundMatch = true;
break;
}
}
if (foundMatch) {
op.returnPassthrough = (String) returnPassthrough;
} else { // no match, treat as if empty.
op.hasReturnPassthroughVoid = true;
op.returnPassthrough = null;
}
}
} else if (this.getDetectPassthroughModelsWithSuffixAndField() != null && op.returnBaseType.length() > this.getPassthroughSuffix().length() && op.returnBaseType.endsWith(this.getPassthroughSuffix())) {
boolean foundMatch = false;
for (CodegenProperty var : cm.vars) {
if (var.name.equals(this.getPassthroughField())) {
foundMatch = true;
break;
}
}
if (foundMatch) {
op.returnPassthrough = this.getPassthroughField();
} else { // no match, treat as if empty.
op.hasReturnPassthroughVoid = true;
op.returnPassthrough = null;
}
}
}
if (!op.hasReturnPassthroughVoid) {
Schema responseSchema = unaliasSchema(ModelUtils.getSchemaFromResponse(openAPI, methodResponse));
ExtendedCodegenProperty cp = null;
if (op.returnPassthrough instanceof String && cm != null) {
cp = (ExtendedCodegenProperty) this.processCodeGenModel(cm).vars.get(1);
} else if (responseSchema != null) {
cp = fromProperty("response", responseSchema, false);
this.processCodegenProperty(cp, "", null);
}
op.returnBaseTypeAlternate = null;
if (cp != null) {
op.returnTypeAlternate = cp.dataTypeAlternate;
op.returnTypeIsModel = cp.isModel;
op.returnTypeIsArray = cp.isArray;
if (cp.isArray) {
if (cp.items.isModel) {
op.returnTypeSupportsEntities = true;
op.returnBaseTypeAlternate = cp.items.dataType + "Record";
} else if (cp.items.allowableValues != null) {
op.returnBaseTypeAlternate = cp.items.dataType;
}
} else if (cp.isModel) {
op.returnTypeSupportsEntities = true;
op.returnBaseTypeAlternate = cp.dataTypeAlternate;
} else if (cp.allowableValues != null) {
op.returnBaseTypeAlternate = cp.dataTypeAlternate;
}
}
}
}
}
return op;
}
@Override
public String escapeReservedWord(String name) {
if (this.getSagasAndRecords()) {
if (this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
} else {
return super.escapeReservedWord(name);
}
}
@Override
public OperationsMap postProcessOperationsWithModels(OperationsMap operations, List<ModelMap> allModels) {
// Add supporting file only if we plan to generate files in /apis
if (!operations.isEmpty() && !addedApiIndex) {
addedApiIndex = true;
supportingFiles.add(new SupportingFile("apis.index.mustache", apiPackage().replace('.', File.separatorChar), "index.ts"));
if (this.getSagasAndRecords()) {
supportingFiles.add(new SupportingFile("sagaApiManager.mustache", apiPackage().replace('.', File.separatorChar), "SagaApiManager.ts"));
supportingFiles.add(new SupportingFile("allSagas.mustache", apiPackage().replace('.', File.separatorChar), "allSagas.ts"));
}
}
// Add supporting file only if we plan to generate files in /models
if (!allModels.isEmpty() && !addedModelIndex) {
addedModelIndex = true;
supportingFiles.add(new SupportingFile("models.index.mustache", modelPackage().replace('.', File.separatorChar), "index.ts"));
}
this.addOperationModelImportInformation(operations);
this.updateOperationParameterForEnum(operations);
if (this.getSagasAndRecords()) {
this.updateOperationParameterForSagaAndRecords(operations);
}
this.addOperationObjectResponseInformation(operations);
this.addOperationPrefixParameterInterfacesInformation(operations);
this.escapeOperationIds(operations);
return operations;
}
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
Map<String, Object> parentObjs = super.postProcessSupportingFileData(objs);
parentObjs.put("useSagaAndRecords", this.getSagasAndRecords());
return parentObjs;
}
private ExtendedCodegenModel processCodeGenModel(ExtendedCodegenModel cm) {
if (this.getSagasAndRecords()) {
Object xEntityId = cm.vendorExtensions.get(X_ENTITY_ID);
if (xEntityId == null && this.getInferEntityFromUniqueIdWithName() != null) {
xEntityId = this.getInferEntityFromUniqueIdWithName();
}
Object vendorKeepAsJSObject = cm.vendorExtensions.get(X_KEEP_AS_JS_OBJECT);
String[] propertiesToKeepAsJSObject = null;
if (vendorKeepAsJSObject instanceof String) {
propertiesToKeepAsJSObject = ((String) vendorKeepAsJSObject).split(",");
}
for (CodegenProperty cpVar : cm.vars) {
ExtendedCodegenProperty var = (ExtendedCodegenProperty) cpVar;
if (propertiesToKeepAsJSObject != null && Arrays.asList(propertiesToKeepAsJSObject).contains(var.name)) {
var.keepAsJSObject = true;
}
boolean parentIsEntity = this.processCodegenProperty(var, cm.classname, xEntityId);
if (parentIsEntity) {
cm.isEntity = true;
}
}
Object returnPassthrough = cm.vendorExtensions.get(X_OPERATION_RETURN_PASSTHROUGH);
if (returnPassthrough instanceof String) {
if (((String) returnPassthrough).isEmpty()) {
cm.hasReturnPassthroughVoid = true;
cm.returnPassthrough = null;
} else {
boolean foundMatch = false;
for (CodegenProperty var : cm.vars) {
if (var.name.equals(returnPassthrough)) {
foundMatch = true;
break;
}
}
if (foundMatch) {
cm.returnPassthrough = (String) returnPassthrough;
} else { // no match, treat as if empty.
cm.hasReturnPassthroughVoid = true;
cm.returnPassthrough = null;
}
}
} else if (this.getDetectPassthroughModelsWithSuffixAndField() != null && cm.name.length() > this.getPassthroughSuffix().length() && cm.name.endsWith(this.getPassthroughSuffix())) {
boolean foundMatch = false;
for (CodegenProperty var : cm.vars) {
if (var.name.equals(this.getPassthroughField())) {
foundMatch = true;
break;
}
}
if (foundMatch) {
cm.returnPassthrough = this.getPassthroughField();
} else { // no match, treat as if empty.
cm.hasReturnPassthroughVoid = true;
cm.returnPassthrough = null;
}
}
} else {
for (CodegenProperty cpVar : cm.vars) {
ExtendedCodegenProperty var = (ExtendedCodegenProperty) cpVar;
this.processCodegenProperty(var, cm.classname, null);
}
}
if (cm.parent != null) {
for (CodegenProperty cpVar : cm.allVars) {
ExtendedCodegenProperty var = (ExtendedCodegenProperty) cpVar;
if (Boolean.TRUE.equals(var.isEnum)) {
var.datatypeWithEnum = var.datatypeWithEnum
.replace(var.enumName, cm.classname + var.enumName);
}
}
}
if (!cm.oneOf.isEmpty()) {
// For oneOfs only import $refs within the oneOf
TreeSet<String> oneOfRefs = new TreeSet<>();
for (String im : cm.imports) {
if (cm.oneOf.contains(im)) {
oneOfRefs.add(im);
}
}
cm.imports = oneOfRefs;
}
return cm;
}
private boolean processCodegenProperty(ExtendedCodegenProperty var, String parentClassName, Object xEntityId) {
// name enum with model name, e.g. StatusEnum => PetStatusEnum
if (Boolean.TRUE.equals(var.isEnum)) {
// behaviour for enum names is specific for Typescript Fetch, not using namespaces
var.datatypeWithEnum = var.datatypeWithEnum.replace(var.enumName, parentClassName + var.enumName);
// need to post-process defaultValue, was computed with previous var.datatypeWithEnum
if (var.defaultValue != null && !var.defaultValue.equals("undefined")) {
int dotPos = var.defaultValue.indexOf(".");
if (dotPos != -1) {
var.defaultValue = var.datatypeWithEnum + var.defaultValue.substring(dotPos);
}
}
}
boolean parentIsEntity = false;
if (this.getSagasAndRecords()) {
if (var.vendorExtensions.get(X_IS_UNIQUE_ID) instanceof Boolean) {
var.isUniqueId = Boolean.TRUE.equals(var.vendorExtensions.get(X_IS_UNIQUE_ID));
} else if (this.getInferUniqueIdFromNameSuffix() && (var.isArray && "number".equals(var.items.dataType)) || ("number".equals(var.dataType))) {
var.isUniqueId = this.isUniqueIdAccordingToNameSuffix(var.name);
}
if (var.isUniqueId && xEntityId != null && xEntityId.equals(var.name)) {
parentIsEntity = true;
}
var.dataTypeAlternate = var.dataType;
if (var.isArray) {
var.isUniqueId = var.isUniqueId || var.itemsAreUniqueId();
var.dataTypeAlternate = var.dataType.replace("Array<", "List<");
String newItemsDataType = var.getItemsDataType();
if (var.items.isModel) {
newItemsDataType = var.items.dataType + "Record";
var.dataTypeAlternate = var.dataTypeAlternate.replace(var.items.dataType, newItemsDataType);
} else if (var.items.isEnum) {
newItemsDataType = var.items.datatypeWithEnum;
var.dataTypeAlternate = var.dataTypeAlternate.replace(var.items.dataType, newItemsDataType);
} else if (var.isUniqueId) {
newItemsDataType = "string";
var.dataTypeAlternate = var.dataTypeAlternate.replace("number", newItemsDataType);
}
if (var.itemsAreNullable()) {
var.dataTypeAlternate = var.dataTypeAlternate.replace(newItemsDataType, newItemsDataType + " | null");
}
} else if (var.isEnum) {
var.dataTypeAlternate = var.datatypeWithEnum;
} else if (var.isModel) {
var.dataTypeAlternate = var.dataType + "Record";
} else if (var.isUniqueId) {
var.dataTypeAlternate = "string";
if (var.isNullable) {
var.dataTypeAlternate = var.dataTypeAlternate + " | null";
}
}
if (var.defaultValue == null || var.defaultValue.equals("undefined")) {
this.autoSetDefaultValueForProperty(var);
}
}
return parentIsEntity;
}
private boolean itemsAreNullable(ExtendedCodegenProperty var) {
return var.items.isNullable || (var.items.items != null && var.items.items.isNullable);
}
private void escapeOperationIds(OperationsMap operations) {
for (CodegenOperation _op : operations.getOperations().getOperation()) {
ExtendedCodegenOperation op = (ExtendedCodegenOperation) _op;
String param = op.operationIdCamelCase + "Request";
if (op.imports.contains(param)) {
// we import a model with the same name as the generated operation, escape it
op.operationIdCamelCase += "Operation";
op.operationIdLowerCase += "operation";
op.operationIdSnakeCase += "_operation";
}
}
}
private void addOperationModelImportInformation(OperationsMap operations) {
// This method will add extra information to the operations.imports array.
// The api template uses this information to import all the required
// models for a given operation.
List<Map<String, String>> imports = operations.getImports();
List<String> existingRecordClassNames = new ArrayList<>();
List<String> existingClassNames = new ArrayList<>();
for (Map<String, String> im : imports) {
String className = im.get("import").replace(modelPackage() + ".", "");
existingClassNames.add(className);
existingRecordClassNames.add(className + "Record");
im.put("className", className);
}
if (this.getSagasAndRecords()) {
Set<String> additionalPassthroughImports = new TreeSet<>();
for (CodegenOperation _op : operations.getOperations().getOperation()) {
ExtendedCodegenOperation op = (ExtendedCodegenOperation) _op;
if (op.returnPassthrough != null && op.returnBaseTypeAlternate != null) {
if (op.returnTypeSupportsEntities && !existingRecordClassNames.contains(op.returnBaseTypeAlternate)) {
additionalPassthroughImports.add(op.returnBaseTypeAlternate);
} else if (!op.returnTypeSupportsEntities && !existingClassNames.contains(op.returnBaseTypeAlternate)) {
additionalPassthroughImports.add(op.returnBaseTypeAlternate);
}
}
}
operations.put("passthroughImports", additionalPassthroughImports);
operations.put("hasPassthroughImports", additionalPassthroughImports.size() > 0);
}
}
private void updateOperationParameterForEnum(OperationsMap operations) {
// This method will add extra information as to whether or not we have enums and
// update their names with the operation.id prefixed.
// It will also set the uniqueId status if provided.
boolean hasEnum = false;
for (CodegenOperation _op : operations.getOperations().getOperation()) {
ExtendedCodegenOperation op = (ExtendedCodegenOperation) _op;
for (CodegenParameter cpParam : op.allParams) {
ExtendedCodegenParameter param = (ExtendedCodegenParameter) cpParam;
if (Boolean.TRUE.equals(param.isEnum)) {
hasEnum = true;
param.datatypeWithEnum = param.datatypeWithEnum
.replace(param.enumName, op.operationIdCamelCase + param.enumName);
}
}
}
operations.put("hasEnums", hasEnum);
}
private void updateOperationParameterForSagaAndRecords(OperationsMap operations) {
// This method will add extra information as to whether or not we have enums and
// update their names with the operation.id prefixed.
// It will also set the uniqueId status if provided.
for (CodegenOperation _op : operations.getOperations().getOperation()) {
ExtendedCodegenOperation op = (ExtendedCodegenOperation) _op;
for (CodegenParameter cpParam : op.allParams) {
ExtendedCodegenParameter param = (ExtendedCodegenParameter) cpParam;
if (param.vendorExtensions.get(X_IS_UNIQUE_ID) instanceof Boolean) {
param.isUniqueId = Boolean.TRUE.equals(param.vendorExtensions.get(X_IS_UNIQUE_ID));
} else if (this.getInferUniqueIdFromNameSuffix() && (param.isArray && "number".equals(param.items.dataType)) || ("number".equals(param.dataType))) {
param.isUniqueId = this.isUniqueIdAccordingToNameSuffix(param.paramName);
}
param.dataTypeAlternate = param.dataType;
if (param.isArray) {
param.isUniqueId = param.isUniqueId || param.itemsAreUniqueId();
param.dataTypeAlternate = param.dataType.replace("Array<", "List<");
String newItemsDataType = param.getItemsDataType();
if (param.items.isModel) {
newItemsDataType = param.items.dataType + "Record";
param.dataTypeAlternate = param.dataTypeAlternate.replace(param.items.dataType, newItemsDataType);
} else if (param.items.isEnum) {
newItemsDataType = param.datatypeWithEnum.substring(param.datatypeWithEnum.lastIndexOf("<") + 1, param.datatypeWithEnum.indexOf(">"));
param.dataTypeAlternate = param.datatypeWithEnum.replace("Array<", "List<");
} else if (param.isUniqueId) {
newItemsDataType = "string";
param.dataTypeAlternate = param.dataTypeAlternate.replace("number", newItemsDataType);
}
if (param.itemsAreNullable()) {
param.dataTypeAlternate = param.dataTypeAlternate.replace(newItemsDataType, newItemsDataType + " | null");
}
} else if (param.isEnum) {
param.dataTypeAlternate = param.datatypeWithEnum;
} else if (param.isModel) {
param.dataTypeAlternate = param.dataType + "Record";
} else if (param.isUniqueId) {
param.dataTypeAlternate = "string";
if (param.isNullable) {
param.dataTypeAlternate = param.dataTypeAlternate + " | null";
}
}
}
}
}
private void addOperationObjectResponseInformation(OperationsMap operations) {
// This method will modify the information on the operations' return type.
// The api template uses this information to know when to return a text
// response for a given simple response operation.
for (CodegenOperation _op : operations.getOperations().getOperation()) {
ExtendedCodegenOperation op = (ExtendedCodegenOperation) _op;
if ("object".equals(op.returnType)) {
op.isMap = true;
op.returnSimpleType = false;
}
}
}
private void addOperationPrefixParameterInterfacesInformation(Map<String, Object> operations) {
operations.put("prefixParameterInterfaces", getPrefixParameterInterfaces());
}
private void addExtraReservedWords() {
this.reservedWords.add("BASE_PATH");
this.reservedWords.add("BaseAPI");
this.reservedWords.add("RequiredError");
this.reservedWords.add("COLLECTION_FORMATS");
this.reservedWords.add("FetchAPI");