@devlearning/swagger-generator 1.0.26 → 1.0.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/.vscode/launch.json +28 -22
  2. package/README.md +209 -209
  3. package/dist/api.constants.js +22 -22
  4. package/dist/generators-writers/angular/api-angular-writer.js +15 -15
  5. package/dist/generators-writers/angular/constants.js +24 -24
  6. package/dist/generators-writers/angular/model-angular-writer.js +6 -6
  7. package/dist/generators-writers/nextjs/api-nextjs-writer.js +12 -12
  8. package/dist/generators-writers/nextjs/constants.js +4 -4
  9. package/dist/generators-writers/nextjs/model-nextjs-writer.js +6 -6
  10. package/dist/models/swagger-component-property.js +1 -0
  11. package/dist/models/swagger-component.js +1 -0
  12. package/dist/models/swagger-content.js +1 -0
  13. package/dist/models/swagger-info.js +1 -0
  14. package/dist/models/swagger-method.js +1 -0
  15. package/dist/models/swagger-schema.js +1 -0
  16. package/dist/models/swagger.js +1 -0
  17. package/package.json +45 -45
  18. package/src/api.constants.ts +26 -26
  19. package/src/generator-old.ts +449 -449
  20. package/src/generator.ts +582 -582
  21. package/src/generators-writers/angular/api-angular-writer.ts +141 -141
  22. package/src/generators-writers/angular/constants.ts +36 -36
  23. package/src/generators-writers/angular/model-angular-writer.ts +62 -62
  24. package/src/generators-writers/dart/api-dart-writer.ts +190 -190
  25. package/src/generators-writers/dart/model-dart-writer.ts +162 -162
  26. package/src/generators-writers/dart/models/import-definition-dart.ts +5 -5
  27. package/src/generators-writers/dart/normalizator.ts +72 -72
  28. package/src/generators-writers/dart/templates/api.mustache +36 -36
  29. package/src/generators-writers/dart/templates/enum.mustache +14 -13
  30. package/src/generators-writers/dart/templates/model.mustache +17 -17
  31. package/src/generators-writers/nextjs/api-nextjs-writer.ts +156 -156
  32. package/src/generators-writers/nextjs/constants.ts +5 -5
  33. package/src/generators-writers/nextjs/model-nextjs-writer.ts +61 -61
  34. package/src/generators-writers/utils.ts +78 -78
  35. package/src/index.ts +96 -96
  36. package/src/models/api-dto.ts +17 -17
  37. package/src/models/enum-value-dto.ts +3 -3
  38. package/src/models/model-dto.ts +9 -9
  39. package/src/models/parameter-dto.ts +7 -7
  40. package/src/models/property-dto.ts +4 -4
  41. package/src/models/swagger/swagger-component-property.ts +11 -11
  42. package/src/models/swagger/swagger-component.ts +17 -17
  43. package/src/models/swagger/swagger-content.ts +4 -4
  44. package/src/models/swagger/swagger-info.ts +3 -3
  45. package/src/models/swagger/swagger-method.ts +7 -7
  46. package/src/models/swagger/swagger-schema.ts +20 -20
  47. package/src/models/swagger/swagger.ts +38 -38
  48. package/src/models/type-dto.ts +7 -7
  49. package/src/swagger-downloader.ts +12 -12
  50. package/tsconfig.json +28 -28
  51. package/autogen/identity/api/identity_api.dart +0 -100
  52. package/autogen/identity/models/auth_activate_command.dart +0 -14
  53. package/autogen/identity/models/auth_app_authenticate_command.dart +0 -16
  54. package/autogen/identity/models/auth_generate_reset_password_code_command.dart +0 -15
  55. package/autogen/identity/models/auth_refresh_token_command.dart +0 -15
  56. package/autogen/identity/models/auth_reset_password_command.dart +0 -16
  57. package/autogen/identity/models/auth_user_authenticate_command.dart +0 -15
  58. package/autogen/identity/models/auth_user_dto.dart +0 -18
  59. package/autogen/identity/models/auth_verify_reset_password_code_command.dart +0 -14
  60. package/autogen/identity/models/authentication_token.dart +0 -17
  61. package/autogen/mvc/models/problem_details.dart +0 -17
  62. package/autogen/product/api/product_api.dart +0 -70
  63. package/autogen/product/models/geoposition.dart +0 -14
  64. package/autogen/product/models/product_category_dto.dart +0 -15
  65. package/autogen/product/models/product_category_list_query_response.dart +0 -14
  66. package/autogen/product/models/product_category_save_command.dart +0 -15
  67. package/autogen/product/models/product_list_nearby_query.dart +0 -20
  68. package/autogen/product/models/product_list_nearby_query_filter.dart +0 -15
  69. package/autogen/product/models/product_list_nearby_query_order_by.dart +0 -10
  70. package/autogen/product/models/product_save_command.dart +0 -13
  71. package/autogen/service_defaults/models/application_exception.dart +0 -14
  72. package/autogen/service_defaults/models/result.dart +0 -17
  73. package/autogen/service_defaults/models/sort_direction.dart +0 -10
  74. package/autogen/user_profile/api/user_profile_api.dart +0 -51
  75. package/autogen/user_profile/models/user_general_info_save_command.dart +0 -17
  76. package/dist/generators-writers/dart/templates/api.mustache +0 -36
  77. package/dist/generators-writers/dart/templates/enum.mustache +0 -14
  78. package/dist/generators-writers/dart/templates/model.mustache +0 -18
package/src/generator.ts CHANGED
@@ -1,583 +1,583 @@
1
- import fs from 'fs';
2
- import { SwaggerComponent } from './models/swagger/swagger-component.js';
3
- import { Swagger } from './models/swagger/swagger.js';
4
- import { SwaggerMethod } from './models/swagger/swagger-method.js';
5
- import { SwaggerSchema } from './models/swagger/swagger-schema.js';
6
- import { ApiDto } from './models/api-dto.js';
7
- import { TypeDto } from './models/type-dto.js';
8
- import { ParameterDto } from './models/parameter-dto.js';
9
- import { ApiNextJsWriter } from './generators-writers/nextjs/api-nextjs-writer.js';
10
- import { ApiAngularWriter } from './generators-writers/angular/api-angular-writer.js';
11
- import { ModelDto } from './models/model-dto.js';
12
- import { SingleBar, Presets } from 'cli-progress';
13
- import { ModelNextJsWriter } from './generators-writers/nextjs/model-nextjs-writer.js';
14
- import { ModelAngularWriter } from './generators-writers/angular/model-angular-writer.js';
15
- import { PropertyDto } from './models/property-dto.js';
16
- import { EnumValueDto } from './models/enum-value-dto.js';
17
- import { SwaggerContent } from './models/swagger/swagger-content.js';
18
- import { CommandLineArgs, DateTimeLibrary, TargetGeneration } from './index.js';
19
- import { ApiDartWriter } from './generators-writers/dart/api-dart-writer.js';
20
- import { ModelDartWriter } from './generators-writers/dart/model-dart-writer.js';
21
- import { Utils } from './generators-writers/utils.js';
22
-
23
- const contentTypeApplicationJson = 'application/json';
24
- const contentTypeMultipartFormData = 'multipart/form-data';
25
-
26
- export class Generator {
27
- private _swagger: Swagger;
28
- private _commandLineArgs: CommandLineArgs;
29
-
30
- private _apis: ApiDto[] = [];
31
- private _models: ModelDto[] = [];
32
-
33
- private _barApis = new SingleBar({
34
- format: '{bar} {percentage}% | {message} {value}/{total} Elapsed: {duration_formatted}', // Formato della barra
35
- barCompleteChar: '\u2588', // Carattere pieno per la barra
36
- barIncompleteChar: '\u2591', // Carattere vuoto per la parte non completata
37
- hideCursor: true, // Nascondi il cursore durante l'esecuzione
38
- barsize: 20,
39
- }, Presets.shades_classic);
40
-
41
- private _barModels = new SingleBar({
42
- format: '{bar} {percentage}% | {message} {value}/{total} Elapsed: {duration_formatted}', // Formato della barra
43
- barCompleteChar: '\u2588', // Carattere pieno per la barra
44
- barIncompleteChar: '\u2591', // Carattere vuoto per la parte non completata
45
- hideCursor: true, // Nascondi il cursore durante l'esecuzione
46
- barsize: 20,
47
- }, Presets.shades_classic);
48
-
49
- constructor(swagger: Swagger, commandLineArgs: CommandLineArgs) {
50
- this._swagger = swagger;
51
- this._commandLineArgs = commandLineArgs;
52
- }
53
-
54
- generate() {
55
- console.info('%c[Swagger API Generator] %cStarting to parse Swagger JSON file...', 'color: #4CAF50; font-weight: bold;', 'color: #2196F3;');
56
-
57
- Utils.clearDirectory(this._commandLineArgs.outputDirectory);
58
-
59
- this.computeApi();
60
- this.computeModel();
61
-
62
- this.generateModel();
63
- this.generateApi();
64
-
65
- console.info('%c[Swagger Generator] %cSwagger file generated successfully!', 'color: #4CAF50; font-weight: bold;', 'color: #00C853;');
66
- }
67
-
68
- computeApi() {
69
- this._barApis.start(Object.getOwnPropertyNames(this._swagger.paths).length, 0);
70
- for (let index = 0; index < Object.getOwnPropertyNames(this._swagger.paths).length; index++) {
71
- const apiName = Object.getOwnPropertyNames(this._swagger.paths)[index];
72
- this._barApis.update(index, { message: `Apis parsing... ${apiName}` });
73
- const apiSwaggerMethodKey = this._swagger.paths[apiName];
74
- const apiMethod = Object.getOwnPropertyNames(apiSwaggerMethodKey)[0];
75
- const apiSwaggerMethod = apiSwaggerMethodKey[apiMethod];
76
-
77
- let apiDto: ApiDto = {
78
- name: apiName,
79
- url: apiName.replace('{version}', '1'),
80
- method: apiMethod,
81
- parameters: this.computeParameters(apiName, apiSwaggerMethod),
82
- returnType: this.computeResponseType(apiSwaggerMethod),
83
- swaggerMethodKey: apiSwaggerMethodKey,
84
- swaggerMethod: apiSwaggerMethod,
85
- haveRequest: apiSwaggerMethod.requestBody != null,
86
- isMultiPart: apiSwaggerMethod.requestBody != null && apiSwaggerMethod.requestBody.content[contentTypeMultipartFormData] != null,
87
- tag: apiSwaggerMethod.tags && apiSwaggerMethod.tags.length > 0 ? apiSwaggerMethod.tags[0] : 'default',
88
- };
89
- this._apis.push(apiDto);
90
- }
91
- }
92
-
93
- computeModel() {
94
- this._barModels.start(Object.getOwnPropertyNames(this._swagger.paths).length, 0);
95
-
96
- let usedTypes: TypeDto[] = [];
97
- let usedMultiPart: string[] = [];
98
-
99
- // for (let index = 0; index < Object.getOwnPropertyNames(this._swagger.paths).length; index++) {
100
- // const apiName = Object.getOwnPropertyNames(this._swagger.paths)[index];
101
- // const apiSwaggerMethodKey = this._swagger.paths[apiName];
102
- // const apiMethod = Object.getOwnPropertyNames(apiSwaggerMethodKey)[0];
103
- // const apiSwaggerMethod = apiSwaggerMethodKey[apiMethod];
104
-
105
- // const parametersRefType = apiSwaggerMethod.parameters?.filter(x => x.in == 'query' && x.schema?.$ref != null).map(x => x.schema.$ref.replace('#/components/schemas/', ''));
106
- // if (parametersRefType) {
107
- // usedTypes = usedTypes.concat(parametersRefType);
108
- // }
109
-
110
- // const responseRefType = this.computeRequestBodyType(apiSwaggerMethod!);
111
- // if (responseRefType && !responseRefType.isVoid && !responseRefType.isNativeType) {
112
- // usedTypes = usedTypes.concat(responseRefType.typeName);
113
- // }
114
-
115
- // const contentRefType = this.computeResponseType(apiSwaggerMethod!);
116
- // if (contentRefType && !contentRefType.isVoid && !contentRefType.isNativeType) {
117
- // usedTypes = usedTypes.concat(contentRefType.typeName);
118
- // }
119
- // }
120
-
121
- for (let index = 0; index < this._apis.length; index++) {
122
- if (this._apis[index].returnType && this._apis[index].returnType!.isTypeReference) {
123
- usedTypes.push(this._apis[index].returnType!);
124
- }
125
-
126
- if (this._apis[index].parameters) {
127
- this._apis[index].parameters.forEach(parameter => {
128
- if (parameter.isTypeReference) {
129
- usedTypes.push(parameter);
130
- }
131
- });
132
- }
133
- }
134
-
135
- usedTypes = [...new Set(usedTypes.map(item => item))]; // distinct
136
-
137
- this.retrieveNestedObjects(usedTypes);
138
-
139
- let models = ``;
140
- if (this._swagger.components != null
141
- && this._swagger.components != undefined
142
- && this._swagger.components.schemas != null
143
- && this._swagger.components.schemas != undefined) {
144
-
145
- for (let index = 0; index < Object.getOwnPropertyNames(this._swagger.components.schemas).length; index++) {
146
- const modelName = Object.getOwnPropertyNames(this._swagger.components.schemas)[index];
147
-
148
- const swaggerComponent = this._swagger.components.schemas[modelName];
149
-
150
- this._models.push({
151
- typeName: modelName,
152
- modelType: swaggerComponent.type == 'integer' ? 'enum' : 'class',
153
- name: modelName,
154
- properties: (swaggerComponent.type == 'object') ? this.retrieveComponentProperties(swaggerComponent) : [],
155
- enumValues: (swaggerComponent.type == 'integer') ? this.retrieveEnumValues(modelName, swaggerComponent) : [],
156
- });
157
- }
158
-
159
- }
160
-
161
- usedMultiPart.forEach(apiName => {
162
- const swaggerMethod = this._swagger.paths[apiName];
163
- const method = Object.getOwnPropertyNames(swaggerMethod)[0];
164
- const swaggerMethodInfo = swaggerMethod[method];
165
-
166
- throw new Error(`MultiPart FormData is not supported yet for ${apiName} - ${method}.`);
167
- // this._models.push({
168
- // typeName: this.getApiNameNormalized(apiName),
169
- // modelType: 'class',
170
- // name: this.getApiNameNormalized(apiName),
171
- // properties: this.retrieveComponentProperties(swaggerMethodInfo.requestBody.content[contentTypeMultipartFormData].schema),
172
- // enumValues: [],
173
- // });
174
- });
175
- }
176
-
177
- generateApi() {
178
- this._barApis.update(this._apis.length, { message: `Api generating...` });
179
-
180
- if (this._commandLineArgs.target == TargetGeneration.Angular) {
181
- const apiWriter = new ApiAngularWriter(this._commandLineArgs.outputDirectory);
182
- apiWriter.write(this._apis);
183
- } else if (this._commandLineArgs.target == TargetGeneration.Next) {
184
- const apiWriter = new ApiNextJsWriter(this._commandLineArgs.outputDirectory);
185
- apiWriter.write(this._apis);
186
- } else if (this._commandLineArgs.target == TargetGeneration.Flutter) {
187
- const apiWriter = new ApiDartWriter(this._commandLineArgs);
188
- apiWriter.write(this._apis, this._models);
189
- }
190
-
191
- this._barApis.update(this._apis.length, { message: `Api was generated successfully` });
192
-
193
- this._barApis.stop();
194
- }
195
-
196
-
197
- generateModel() {
198
- this._barModels.update(this._apis.length, { message: `Model generation...` });
199
-
200
- if (this._commandLineArgs.target == TargetGeneration.Angular) {
201
- const apiWriter = new ModelAngularWriter(this._commandLineArgs.outputDirectory);
202
- apiWriter.write(this._models);
203
- } else if (this._commandLineArgs.target == TargetGeneration.Next) {
204
- const apiWriter = new ModelNextJsWriter(this._commandLineArgs.outputDirectory);
205
- apiWriter.write(this._models);
206
- } else if (this._commandLineArgs.target == TargetGeneration.Flutter) {
207
- const apiWriter = new ModelDartWriter(this._commandLineArgs);
208
- apiWriter.write(this._models);
209
- }
210
-
211
- this._barModels.update(this._apis.length, { message: `Model was generated successfully` });
212
-
213
- this._barModels.stop();
214
- }
215
-
216
- computeParameters(apiName: string, swaggerMethod: SwaggerMethod | undefined) {
217
- if (!apiName) return [];
218
- if (!swaggerMethod || swaggerMethod == null) return [];
219
-
220
- let parameters: ParameterDto[] = [];
221
- try {
222
- if (swaggerMethod.requestBody != null && swaggerMethod.requestBody.content[contentTypeMultipartFormData] != null) {
223
- var modelName = this.getApiNameNormalized(apiName);
224
- parameters.push({
225
- name: 'request',
226
- typeName: modelName,
227
- nullable: false,
228
- isQuery: false,
229
- isEnum: false,
230
- isTypeReference: true,
231
- isNativeType: false,
232
- isArray: false,
233
- isVoid: false,
234
- });
235
- } else {
236
- if (swaggerMethod.requestBody != null) {
237
- const type = this.retrieveType(swaggerMethod.requestBody.content[contentTypeApplicationJson].schema);
238
- parameters.push({
239
- name: 'request',
240
- typeName: type.typeName, //swaggerMethod.requestBody.content[contentTypeApplicationJson].schema.$ref.replace('#/components/schemas/', ''),
241
- nullable: false,
242
- isQuery: false,
243
- isEnum: false,
244
- isTypeReference: true,
245
- isNativeType: false,
246
- isArray: false,
247
- isVoid: false,
248
- });
249
- } else {
250
- swaggerMethod.parameters?.filter(x => x.in == 'query').forEach(parameter => {
251
- if (parameter.schema.$ref != null) {
252
- const type = this.retrieveType(parameter.schema);
253
- parameters.push({
254
- name: this.toFirstLetterLowercase(parameter.name),
255
- typeName: type.typeName, //parameter.schema.$ref.replace('#/components/schemas/', ''),
256
- nullable: !parameter.required,
257
- swaggerParameter: parameter,
258
- isQuery: true,
259
- isEnum: this.isEnum(parameter.schema.$ref),
260
- isTypeReference: false,
261
- isNativeType: false,
262
- isArray: false,
263
- isVoid: false,
264
- });
265
- } else {
266
- parameters.push({
267
- name: this.toFirstLetterLowercase(parameter.name),
268
- typeName: this.getNativeType(parameter.schema),
269
- nullable: !parameter.required,
270
- swaggerParameter: parameter,
271
- isQuery: true,
272
- isEnum: false,
273
- isTypeReference: false,
274
- isNativeType: true,
275
- isArray: false,
276
- isVoid: false,
277
- });
278
- }
279
- });
280
- }
281
- }
282
- } catch (error) {
283
- console.error(`\t\tError in ${apiName} - Attenzione forse hai dimenticato IActionResult e non hai tipizzato il tipo restituito dal servizio`);
284
- }
285
- return parameters;
286
- }
287
-
288
- computeResponseType(swaggerMethod: SwaggerMethod) {
289
- if (swaggerMethod.responses[200] == null) {
290
- return <TypeDto>{
291
- typeName: 'void',
292
- nullable: false,
293
- isVoid: true,
294
- }
295
- }
296
-
297
- return this.computeSwaggerContentType(swaggerMethod.responses[200].content[contentTypeApplicationJson]);
298
- }
299
-
300
- computeRequestBodyType(swaggerMethod: SwaggerMethod) {
301
- if (swaggerMethod.requestBody == null) {
302
- return <TypeDto>{
303
- typeName: 'void',
304
- nullable: false,
305
- isVoid: true,
306
- }
307
- }
308
-
309
- return this.computeSwaggerContentType(swaggerMethod.requestBody.content[contentTypeApplicationJson]);
310
- }
311
-
312
- computeSwaggerContentType(swaggerContent: SwaggerContent) {
313
- try {
314
- if (swaggerContent.schema.$ref != null)
315
- return <TypeDto>{
316
- typeName: this.getObjectName(swaggerContent.schema.$ref),
317
- nullable: false,
318
- isNativeType: false,
319
- };
320
- } catch (error) {
321
- const errorMessage = "\t\tAttenzione forse hai dimenticato IActionResult e non hai tipizzato il tipo restituito dal servizio";
322
- console.error(`%c${errorMessage}`, 'color: red');
323
- throw new Error(errorMessage);
324
- }
325
-
326
- if (swaggerContent.schema.type != null) {
327
- let schema = swaggerContent.schema;
328
- if (schema.type == 'array') {
329
- if (schema.items?.$ref != null) {
330
- return <TypeDto>{
331
- typeName: `${this.getObjectName(schema.items.$ref)}`,
332
- nullable: false,
333
- isNativeType: false,
334
- isArray: true,
335
- };
336
- }
337
- } else {
338
- return <TypeDto>{
339
- typeName: this.getNativeType(swaggerContent.schema),
340
- nullable: false,
341
- isNativeType: true,
342
- };
343
- }
344
- // if (swaggerComponentProperty.items.$ref != null)
345
- // return `${this.getObjectName(swaggerComponentProperty.items.$ref)}[]`;
346
-
347
-
348
- } else {
349
- return <TypeDto>{
350
- typeName: this.getNativeType(swaggerContent.schema),
351
- nullable: false,
352
- isNativeType: true,
353
- };
354
- }
355
- }
356
-
357
- retrieveType(swaggerComponentProperty: SwaggerSchema): TypeDto {
358
- if (swaggerComponentProperty.$ref != null) {
359
- return {
360
- typeName: swaggerComponentProperty.$ref.replace('#/components/schemas/', ''),
361
- isTypeReference: true,
362
- isNativeType: false,
363
- nullable: swaggerComponentProperty.nullable ?? false,
364
- isArray: false,
365
- isVoid: false,
366
- };
367
- }
368
-
369
- if (swaggerComponentProperty.allOf != null) {
370
- const type = this.retrieveType(swaggerComponentProperty.allOf[0]); //TODO per ora prendo solo il primo, ma potrebbe essere un array di tipi
371
- return {
372
- ...type,
373
- nullable: swaggerComponentProperty.nullable ?? false,
374
- };
375
- }
376
-
377
- if (swaggerComponentProperty.type != null && swaggerComponentProperty.type == 'array') {
378
- if (swaggerComponentProperty.items?.$ref != null) {
379
- return {
380
- typeName: `${this.getObjectName(swaggerComponentProperty.items.$ref)}`,
381
- isTypeReference: true,
382
- isNativeType: false,
383
- nullable: swaggerComponentProperty.nullable ?? false,
384
- isArray: true,
385
- isVoid: false,
386
- };
387
- }
388
- else {
389
- return {
390
- typeName: this.getNativeType(swaggerComponentProperty),
391
- isTypeReference: false,
392
- isNativeType: true,
393
- nullable: swaggerComponentProperty.nullable ?? false,
394
- isArray: false,
395
- isVoid: false,
396
- };
397
- }
398
- }
399
-
400
- if (swaggerComponentProperty.type != null) {
401
- return {
402
- typeName: this.getNativeType(swaggerComponentProperty),
403
- isTypeReference: false,
404
- isNativeType: true,
405
- nullable: swaggerComponentProperty.nullable ?? false,
406
- isArray: false,
407
- isVoid: false,
408
- };
409
- }
410
- if (swaggerComponentProperty.type == null) {
411
- return {
412
- typeName: 'void',
413
- isTypeReference: false,
414
- isNativeType: false,
415
- nullable: swaggerComponentProperty.nullable ?? false,
416
- isArray: false,
417
- isVoid: true,
418
- };
419
- }
420
- console.error("unmanaged swaggerMethodInfo", swaggerComponentProperty);
421
- throw new Error("unmanaged swaggerMethodInfo");
422
- }
423
-
424
- parametrizeObject(objectName: string) {
425
- let component = this._swagger.components.schemas[this.getObjectName(objectName)];
426
-
427
- if (component == null || component.properties == null) return ``;
428
-
429
- console.debug(component.properties);
430
-
431
- return ``;
432
- }
433
-
434
- isEnum(objectName: string) {
435
- let component = this._swagger.components.schemas[this.getObjectName(objectName)];
436
- return component.enum != null;
437
- }
438
-
439
- isDate(schema: SwaggerSchema) {
440
- return schema.type == 'string' && schema.format == 'date-time';
441
- }
442
-
443
- getObjectName(ref: string) {
444
- return ref.replace('#/components/schemas/', '');
445
- }
446
-
447
- retrieveComponentProperties(swaggerComponent: SwaggerComponent) {
448
- if (swaggerComponent.properties == null) return [];
449
-
450
- let properties: PropertyDto[] = [];
451
- for (let index = 0; index < Object.getOwnPropertyNames(swaggerComponent.properties).length; index++) {
452
- const propertyName = Object.getOwnPropertyNames(swaggerComponent.properties)[index];
453
- const required = swaggerComponent.required && swaggerComponent.required.includes(propertyName);
454
- const type = this.retrieveType(swaggerComponent.properties[propertyName]);
455
- properties.push({
456
- ...type,
457
- name: propertyName,
458
- nullable: required || type.nullable,
459
- });
460
- }
461
-
462
- return properties;
463
- }
464
-
465
- // retrieveSchemaProperties(schema: SwaggerSchema) {
466
- // if (schema.properties == null) return [];
467
-
468
- // let properties: PropertyDto[] = [];
469
- // for (let j = 0; j < Object.getOwnPropertyNames(schema.properties).length; j++) {
470
- // let propertyName = Object.getOwnPropertyNames(schema.properties)[j];
471
- // properties +=
472
- // `
473
- // ${this.toFirstLetterLowercase(propertyName)}: ${this.retrieveType(schema.properties[propertyName])} | undefined;`
474
- // }
475
-
476
- // return properties;
477
- // }
478
-
479
- retrieveEnumValues(name: string, swaggerCopmponent: SwaggerComponent) {
480
- if (swaggerCopmponent.enum == null) return [];
481
-
482
- let values: EnumValueDto[] = [];
483
- for (let index = 0; index < swaggerCopmponent.enum.length; index++) {
484
- try {
485
- values.push({
486
- name: swaggerCopmponent.enum[index].split('-')[0].trim(),
487
- value: swaggerCopmponent.enum[index].split('-')[1].trim(),
488
- });
489
- } catch (error) {
490
- debugger
491
- }
492
-
493
- }
494
-
495
- return values;
496
- }
497
-
498
- retrieveNestedObjects(usedTypes: TypeDto[]) {
499
- for (let i = 0; i < usedTypes.length; i++) {
500
- const swaggerCopmponent = this._swagger.components.schemas[usedTypes[i].typeName];
501
- this.retrieveNestedObjectsRecursive(swaggerCopmponent, usedTypes);
502
- }
503
- }
504
-
505
- retrieveNestedObjectsRecursive(swaggerComponent: SwaggerComponent, usedTypes: TypeDto[]) {
506
- try {
507
- if (!swaggerComponent.properties) return;
508
-
509
- for (let j = 0; j < Object.getOwnPropertyNames(swaggerComponent.properties).length; j++) {
510
- const propertyName = Object.getOwnPropertyNames(swaggerComponent.properties)[j];
511
-
512
- let nestedUsedType = '';
513
-
514
- if (!swaggerComponent.properties[propertyName]) continue;
515
-
516
- if (swaggerComponent.properties[propertyName].$ref) {
517
- nestedUsedType = swaggerComponent.properties[propertyName].$ref!.replace('#/components/schemas/', '');
518
- } else if (swaggerComponent.properties[propertyName].allOf && swaggerComponent.properties[propertyName].allOf![0] && swaggerComponent.properties[propertyName].allOf![0]!.$ref) {
519
- nestedUsedType = swaggerComponent.properties[propertyName].allOf![0]!.$ref!.replace('#/components/schemas/', ''); //TODO Assuming allOf contains a single $ref
520
- } else if (swaggerComponent.properties[propertyName].type == 'array' && swaggerComponent.properties[propertyName].items?.$ref) {
521
- nestedUsedType = swaggerComponent.properties[propertyName].items!.$ref!.replace('#/components/schemas/', '');
522
- }
523
-
524
- if (nestedUsedType != '' && usedTypes.findIndex(x => x.typeName == nestedUsedType) == -1) {
525
- let nested = this._swagger.components.schemas[nestedUsedType];
526
- const required = swaggerComponent.required && swaggerComponent.required.includes(propertyName);
527
- usedTypes.push({
528
- typeName: nestedUsedType,
529
- isTypeReference: nested.type == 'object',
530
- isNativeType: nested.type != 'object',
531
- nullable: required,
532
- isArray: false,
533
- isVoid: false,
534
- //potrebbe essere un enum
535
- });
536
- this.retrieveNestedObjectsRecursive(nested, usedTypes);
537
- }
538
- }
539
- } catch (error) {
540
- debugger
541
- }
542
- }
543
-
544
- getNativeType(schema: SwaggerSchema): string {
545
- let nativeType = 'n.d.';
546
-
547
- if (schema.$ref != null) {
548
- debugger
549
- } else if (schema.type == 'array' && schema.items != null) {
550
- nativeType = this.getNativeType(schema.items);
551
- nativeType += '[]';
552
- } else {
553
- if (schema.type == 'integer') nativeType = 'integer'; //era number
554
- if (schema.type == 'string' && schema.format == null) nativeType = 'string';
555
- if (schema.type == 'string' && schema.format == 'date-time') nativeType = 'dateTime';
556
- if (schema.type == 'string' && schema.format == 'uuid') nativeType = 'string';
557
- if (schema.type == 'string' && schema.format == 'binary') nativeType = 'File';
558
- if (schema.type == 'number') nativeType = 'number';
559
- if (schema.type == 'boolean') nativeType = 'boolean';
560
- if (schema.type == 'object') nativeType = 'any';
561
- }
562
-
563
- if (nativeType.indexOf('n.d') == -1) {
564
- return nativeType;
565
- } else {
566
- console.error("unmanaged schema type", schema);
567
- throw new Error("unmanaged schema");
568
- }
569
- }
570
-
571
- getApiNameNormalized(apiName: string) {
572
- let normalizedApiName = apiName.replace('/api/v{version}/', '').replaceAll('/', '_');
573
-
574
- if (normalizedApiName.charAt(0) == '_') {
575
- normalizedApiName = normalizedApiName.slice(1);
576
- }
577
- return this.toFirstLetterLowercase(normalizedApiName);
578
- }
579
-
580
- toFirstLetterLowercase(value: string) {
581
- return value.charAt(0).toLowerCase() + value.slice(1);
582
- }
1
+ import fs from 'fs';
2
+ import { SwaggerComponent } from './models/swagger/swagger-component.js';
3
+ import { Swagger } from './models/swagger/swagger.js';
4
+ import { SwaggerMethod } from './models/swagger/swagger-method.js';
5
+ import { SwaggerSchema } from './models/swagger/swagger-schema.js';
6
+ import { ApiDto } from './models/api-dto.js';
7
+ import { TypeDto } from './models/type-dto.js';
8
+ import { ParameterDto } from './models/parameter-dto.js';
9
+ import { ApiNextJsWriter } from './generators-writers/nextjs/api-nextjs-writer.js';
10
+ import { ApiAngularWriter } from './generators-writers/angular/api-angular-writer.js';
11
+ import { ModelDto } from './models/model-dto.js';
12
+ import { SingleBar, Presets } from 'cli-progress';
13
+ import { ModelNextJsWriter } from './generators-writers/nextjs/model-nextjs-writer.js';
14
+ import { ModelAngularWriter } from './generators-writers/angular/model-angular-writer.js';
15
+ import { PropertyDto } from './models/property-dto.js';
16
+ import { EnumValueDto } from './models/enum-value-dto.js';
17
+ import { SwaggerContent } from './models/swagger/swagger-content.js';
18
+ import { CommandLineArgs, DateTimeLibrary, TargetGeneration } from './index.js';
19
+ import { ApiDartWriter } from './generators-writers/dart/api-dart-writer.js';
20
+ import { ModelDartWriter } from './generators-writers/dart/model-dart-writer.js';
21
+ import { Utils } from './generators-writers/utils.js';
22
+
23
+ const contentTypeApplicationJson = 'application/json';
24
+ const contentTypeMultipartFormData = 'multipart/form-data';
25
+
26
+ export class Generator {
27
+ private _swagger: Swagger;
28
+ private _commandLineArgs: CommandLineArgs;
29
+
30
+ private _apis: ApiDto[] = [];
31
+ private _models: ModelDto[] = [];
32
+
33
+ private _barApis = new SingleBar({
34
+ format: '{bar} {percentage}% | {message} {value}/{total} Elapsed: {duration_formatted}', // Formato della barra
35
+ barCompleteChar: '\u2588', // Carattere pieno per la barra
36
+ barIncompleteChar: '\u2591', // Carattere vuoto per la parte non completata
37
+ hideCursor: true, // Nascondi il cursore durante l'esecuzione
38
+ barsize: 20,
39
+ }, Presets.shades_classic);
40
+
41
+ private _barModels = new SingleBar({
42
+ format: '{bar} {percentage}% | {message} {value}/{total} Elapsed: {duration_formatted}', // Formato della barra
43
+ barCompleteChar: '\u2588', // Carattere pieno per la barra
44
+ barIncompleteChar: '\u2591', // Carattere vuoto per la parte non completata
45
+ hideCursor: true, // Nascondi il cursore durante l'esecuzione
46
+ barsize: 20,
47
+ }, Presets.shades_classic);
48
+
49
+ constructor(swagger: Swagger, commandLineArgs: CommandLineArgs) {
50
+ this._swagger = swagger;
51
+ this._commandLineArgs = commandLineArgs;
52
+ }
53
+
54
+ generate() {
55
+ console.info('%c[Swagger API Generator] %cStarting to parse Swagger JSON file...', 'color: #4CAF50; font-weight: bold;', 'color: #2196F3;');
56
+
57
+ Utils.clearDirectory(this._commandLineArgs.outputDirectory);
58
+
59
+ this.computeApi();
60
+ this.computeModel();
61
+
62
+ this.generateModel();
63
+ this.generateApi();
64
+
65
+ console.info('%c[Swagger Generator] %cSwagger file generated successfully!', 'color: #4CAF50; font-weight: bold;', 'color: #00C853;');
66
+ }
67
+
68
+ computeApi() {
69
+ this._barApis.start(Object.getOwnPropertyNames(this._swagger.paths).length, 0);
70
+ for (let index = 0; index < Object.getOwnPropertyNames(this._swagger.paths).length; index++) {
71
+ const apiName = Object.getOwnPropertyNames(this._swagger.paths)[index];
72
+ this._barApis.update(index, { message: `Apis parsing... ${apiName}` });
73
+ const apiSwaggerMethodKey = this._swagger.paths[apiName];
74
+ const apiMethod = Object.getOwnPropertyNames(apiSwaggerMethodKey)[0];
75
+ const apiSwaggerMethod = apiSwaggerMethodKey[apiMethod];
76
+
77
+ let apiDto: ApiDto = {
78
+ name: apiName,
79
+ url: apiName.replace('{version}', '1'),
80
+ method: apiMethod,
81
+ parameters: this.computeParameters(apiName, apiSwaggerMethod),
82
+ returnType: this.computeResponseType(apiSwaggerMethod),
83
+ swaggerMethodKey: apiSwaggerMethodKey,
84
+ swaggerMethod: apiSwaggerMethod,
85
+ haveRequest: apiSwaggerMethod.requestBody != null,
86
+ isMultiPart: apiSwaggerMethod.requestBody != null && apiSwaggerMethod.requestBody.content[contentTypeMultipartFormData] != null,
87
+ tag: apiSwaggerMethod.tags && apiSwaggerMethod.tags.length > 0 ? apiSwaggerMethod.tags[0] : 'default',
88
+ };
89
+ this._apis.push(apiDto);
90
+ }
91
+ }
92
+
93
+ computeModel() {
94
+ this._barModels.start(Object.getOwnPropertyNames(this._swagger.paths).length, 0);
95
+
96
+ let usedTypes: TypeDto[] = [];
97
+ let usedMultiPart: string[] = [];
98
+
99
+ // for (let index = 0; index < Object.getOwnPropertyNames(this._swagger.paths).length; index++) {
100
+ // const apiName = Object.getOwnPropertyNames(this._swagger.paths)[index];
101
+ // const apiSwaggerMethodKey = this._swagger.paths[apiName];
102
+ // const apiMethod = Object.getOwnPropertyNames(apiSwaggerMethodKey)[0];
103
+ // const apiSwaggerMethod = apiSwaggerMethodKey[apiMethod];
104
+
105
+ // const parametersRefType = apiSwaggerMethod.parameters?.filter(x => x.in == 'query' && x.schema?.$ref != null).map(x => x.schema.$ref.replace('#/components/schemas/', ''));
106
+ // if (parametersRefType) {
107
+ // usedTypes = usedTypes.concat(parametersRefType);
108
+ // }
109
+
110
+ // const responseRefType = this.computeRequestBodyType(apiSwaggerMethod!);
111
+ // if (responseRefType && !responseRefType.isVoid && !responseRefType.isNativeType) {
112
+ // usedTypes = usedTypes.concat(responseRefType.typeName);
113
+ // }
114
+
115
+ // const contentRefType = this.computeResponseType(apiSwaggerMethod!);
116
+ // if (contentRefType && !contentRefType.isVoid && !contentRefType.isNativeType) {
117
+ // usedTypes = usedTypes.concat(contentRefType.typeName);
118
+ // }
119
+ // }
120
+
121
+ for (let index = 0; index < this._apis.length; index++) {
122
+ if (this._apis[index].returnType && this._apis[index].returnType!.isTypeReference) {
123
+ usedTypes.push(this._apis[index].returnType!);
124
+ }
125
+
126
+ if (this._apis[index].parameters) {
127
+ this._apis[index].parameters.forEach(parameter => {
128
+ if (parameter.isTypeReference) {
129
+ usedTypes.push(parameter);
130
+ }
131
+ });
132
+ }
133
+ }
134
+
135
+ usedTypes = [...new Set(usedTypes.map(item => item))]; // distinct
136
+
137
+ this.retrieveNestedObjects(usedTypes);
138
+
139
+ let models = ``;
140
+ if (this._swagger.components != null
141
+ && this._swagger.components != undefined
142
+ && this._swagger.components.schemas != null
143
+ && this._swagger.components.schemas != undefined) {
144
+
145
+ for (let index = 0; index < Object.getOwnPropertyNames(this._swagger.components.schemas).length; index++) {
146
+ const modelName = Object.getOwnPropertyNames(this._swagger.components.schemas)[index];
147
+
148
+ const swaggerComponent = this._swagger.components.schemas[modelName];
149
+
150
+ this._models.push({
151
+ typeName: modelName,
152
+ modelType: swaggerComponent.type == 'integer' ? 'enum' : 'class',
153
+ name: modelName,
154
+ properties: (swaggerComponent.type == 'object') ? this.retrieveComponentProperties(swaggerComponent) : [],
155
+ enumValues: (swaggerComponent.type == 'integer') ? this.retrieveEnumValues(modelName, swaggerComponent) : [],
156
+ });
157
+ }
158
+
159
+ }
160
+
161
+ usedMultiPart.forEach(apiName => {
162
+ const swaggerMethod = this._swagger.paths[apiName];
163
+ const method = Object.getOwnPropertyNames(swaggerMethod)[0];
164
+ const swaggerMethodInfo = swaggerMethod[method];
165
+
166
+ throw new Error(`MultiPart FormData is not supported yet for ${apiName} - ${method}.`);
167
+ // this._models.push({
168
+ // typeName: this.getApiNameNormalized(apiName),
169
+ // modelType: 'class',
170
+ // name: this.getApiNameNormalized(apiName),
171
+ // properties: this.retrieveComponentProperties(swaggerMethodInfo.requestBody.content[contentTypeMultipartFormData].schema),
172
+ // enumValues: [],
173
+ // });
174
+ });
175
+ }
176
+
177
+ generateApi() {
178
+ this._barApis.update(this._apis.length, { message: `Api generating...` });
179
+
180
+ if (this._commandLineArgs.target == TargetGeneration.Angular) {
181
+ const apiWriter = new ApiAngularWriter(this._commandLineArgs.outputDirectory);
182
+ apiWriter.write(this._apis);
183
+ } else if (this._commandLineArgs.target == TargetGeneration.Next) {
184
+ const apiWriter = new ApiNextJsWriter(this._commandLineArgs.outputDirectory);
185
+ apiWriter.write(this._apis);
186
+ } else if (this._commandLineArgs.target == TargetGeneration.Flutter) {
187
+ const apiWriter = new ApiDartWriter(this._commandLineArgs);
188
+ apiWriter.write(this._apis, this._models);
189
+ }
190
+
191
+ this._barApis.update(this._apis.length, { message: `Api was generated successfully` });
192
+
193
+ this._barApis.stop();
194
+ }
195
+
196
+
197
+ generateModel() {
198
+ this._barModels.update(this._apis.length, { message: `Model generation...` });
199
+
200
+ if (this._commandLineArgs.target == TargetGeneration.Angular) {
201
+ const apiWriter = new ModelAngularWriter(this._commandLineArgs.outputDirectory);
202
+ apiWriter.write(this._models);
203
+ } else if (this._commandLineArgs.target == TargetGeneration.Next) {
204
+ const apiWriter = new ModelNextJsWriter(this._commandLineArgs.outputDirectory);
205
+ apiWriter.write(this._models);
206
+ } else if (this._commandLineArgs.target == TargetGeneration.Flutter) {
207
+ const apiWriter = new ModelDartWriter(this._commandLineArgs);
208
+ apiWriter.write(this._models);
209
+ }
210
+
211
+ this._barModels.update(this._apis.length, { message: `Model was generated successfully` });
212
+
213
+ this._barModels.stop();
214
+ }
215
+
216
+ computeParameters(apiName: string, swaggerMethod: SwaggerMethod | undefined) {
217
+ if (!apiName) return [];
218
+ if (!swaggerMethod || swaggerMethod == null) return [];
219
+
220
+ let parameters: ParameterDto[] = [];
221
+ try {
222
+ if (swaggerMethod.requestBody != null && swaggerMethod.requestBody.content[contentTypeMultipartFormData] != null) {
223
+ var modelName = this.getApiNameNormalized(apiName);
224
+ parameters.push({
225
+ name: 'request',
226
+ typeName: modelName,
227
+ nullable: false,
228
+ isQuery: false,
229
+ isEnum: false,
230
+ isTypeReference: true,
231
+ isNativeType: false,
232
+ isArray: false,
233
+ isVoid: false,
234
+ });
235
+ } else {
236
+ if (swaggerMethod.requestBody != null) {
237
+ const type = this.retrieveType(swaggerMethod.requestBody.content[contentTypeApplicationJson].schema);
238
+ parameters.push({
239
+ name: 'request',
240
+ typeName: type.typeName, //swaggerMethod.requestBody.content[contentTypeApplicationJson].schema.$ref.replace('#/components/schemas/', ''),
241
+ nullable: false,
242
+ isQuery: false,
243
+ isEnum: false,
244
+ isTypeReference: true,
245
+ isNativeType: false,
246
+ isArray: false,
247
+ isVoid: false,
248
+ });
249
+ } else {
250
+ swaggerMethod.parameters?.filter(x => x.in == 'query').forEach(parameter => {
251
+ if (parameter.schema.$ref != null) {
252
+ const type = this.retrieveType(parameter.schema);
253
+ parameters.push({
254
+ name: this.toFirstLetterLowercase(parameter.name),
255
+ typeName: type.typeName, //parameter.schema.$ref.replace('#/components/schemas/', ''),
256
+ nullable: !parameter.required,
257
+ swaggerParameter: parameter,
258
+ isQuery: true,
259
+ isEnum: this.isEnum(parameter.schema.$ref),
260
+ isTypeReference: false,
261
+ isNativeType: false,
262
+ isArray: false,
263
+ isVoid: false,
264
+ });
265
+ } else {
266
+ parameters.push({
267
+ name: this.toFirstLetterLowercase(parameter.name),
268
+ typeName: this.getNativeType(parameter.schema),
269
+ nullable: !parameter.required,
270
+ swaggerParameter: parameter,
271
+ isQuery: true,
272
+ isEnum: false,
273
+ isTypeReference: false,
274
+ isNativeType: true,
275
+ isArray: false,
276
+ isVoid: false,
277
+ });
278
+ }
279
+ });
280
+ }
281
+ }
282
+ } catch (error) {
283
+ console.error(`\t\tError in ${apiName} - Attenzione forse hai dimenticato IActionResult e non hai tipizzato il tipo restituito dal servizio`);
284
+ }
285
+ return parameters;
286
+ }
287
+
288
+ computeResponseType(swaggerMethod: SwaggerMethod) {
289
+ if (swaggerMethod.responses[200] == null) {
290
+ return <TypeDto>{
291
+ typeName: 'void',
292
+ nullable: false,
293
+ isVoid: true,
294
+ }
295
+ }
296
+
297
+ return this.computeSwaggerContentType(swaggerMethod.responses[200].content[contentTypeApplicationJson]);
298
+ }
299
+
300
+ computeRequestBodyType(swaggerMethod: SwaggerMethod) {
301
+ if (swaggerMethod.requestBody == null) {
302
+ return <TypeDto>{
303
+ typeName: 'void',
304
+ nullable: false,
305
+ isVoid: true,
306
+ }
307
+ }
308
+
309
+ return this.computeSwaggerContentType(swaggerMethod.requestBody.content[contentTypeApplicationJson]);
310
+ }
311
+
312
+ computeSwaggerContentType(swaggerContent: SwaggerContent) {
313
+ try {
314
+ if (swaggerContent.schema.$ref != null)
315
+ return <TypeDto>{
316
+ typeName: this.getObjectName(swaggerContent.schema.$ref),
317
+ nullable: false,
318
+ isNativeType: false,
319
+ };
320
+ } catch (error) {
321
+ const errorMessage = "\t\tAttenzione forse hai dimenticato IActionResult e non hai tipizzato il tipo restituito dal servizio";
322
+ console.error(`%c${errorMessage}`, 'color: red');
323
+ throw new Error(errorMessage);
324
+ }
325
+
326
+ if (swaggerContent.schema.type != null) {
327
+ let schema = swaggerContent.schema;
328
+ if (schema.type == 'array') {
329
+ if (schema.items?.$ref != null) {
330
+ return <TypeDto>{
331
+ typeName: `${this.getObjectName(schema.items.$ref)}`,
332
+ nullable: false,
333
+ isNativeType: false,
334
+ isArray: true,
335
+ };
336
+ }
337
+ } else {
338
+ return <TypeDto>{
339
+ typeName: this.getNativeType(swaggerContent.schema),
340
+ nullable: false,
341
+ isNativeType: true,
342
+ };
343
+ }
344
+ // if (swaggerComponentProperty.items.$ref != null)
345
+ // return `${this.getObjectName(swaggerComponentProperty.items.$ref)}[]`;
346
+
347
+
348
+ } else {
349
+ return <TypeDto>{
350
+ typeName: this.getNativeType(swaggerContent.schema),
351
+ nullable: false,
352
+ isNativeType: true,
353
+ };
354
+ }
355
+ }
356
+
357
+ retrieveType(swaggerComponentProperty: SwaggerSchema): TypeDto {
358
+ if (swaggerComponentProperty.$ref != null) {
359
+ return {
360
+ typeName: swaggerComponentProperty.$ref.replace('#/components/schemas/', ''),
361
+ isTypeReference: true,
362
+ isNativeType: false,
363
+ nullable: swaggerComponentProperty.nullable ?? false,
364
+ isArray: false,
365
+ isVoid: false,
366
+ };
367
+ }
368
+
369
+ if (swaggerComponentProperty.allOf != null) {
370
+ const type = this.retrieveType(swaggerComponentProperty.allOf[0]); //TODO per ora prendo solo il primo, ma potrebbe essere un array di tipi
371
+ return {
372
+ ...type,
373
+ nullable: swaggerComponentProperty.nullable ?? false,
374
+ };
375
+ }
376
+
377
+ if (swaggerComponentProperty.type != null && swaggerComponentProperty.type == 'array') {
378
+ if (swaggerComponentProperty.items?.$ref != null) {
379
+ return {
380
+ typeName: `${this.getObjectName(swaggerComponentProperty.items.$ref)}`,
381
+ isTypeReference: true,
382
+ isNativeType: false,
383
+ nullable: swaggerComponentProperty.nullable ?? false,
384
+ isArray: true,
385
+ isVoid: false,
386
+ };
387
+ }
388
+ else {
389
+ return {
390
+ typeName: this.getNativeType(swaggerComponentProperty),
391
+ isTypeReference: false,
392
+ isNativeType: true,
393
+ nullable: swaggerComponentProperty.nullable ?? false,
394
+ isArray: false,
395
+ isVoid: false,
396
+ };
397
+ }
398
+ }
399
+
400
+ if (swaggerComponentProperty.type != null) {
401
+ return {
402
+ typeName: this.getNativeType(swaggerComponentProperty),
403
+ isTypeReference: false,
404
+ isNativeType: true,
405
+ nullable: swaggerComponentProperty.nullable ?? false,
406
+ isArray: false,
407
+ isVoid: false,
408
+ };
409
+ }
410
+ if (swaggerComponentProperty.type == null) {
411
+ return {
412
+ typeName: 'void',
413
+ isTypeReference: false,
414
+ isNativeType: false,
415
+ nullable: swaggerComponentProperty.nullable ?? false,
416
+ isArray: false,
417
+ isVoid: true,
418
+ };
419
+ }
420
+ console.error("unmanaged swaggerMethodInfo", swaggerComponentProperty);
421
+ throw new Error("unmanaged swaggerMethodInfo");
422
+ }
423
+
424
+ parametrizeObject(objectName: string) {
425
+ let component = this._swagger.components.schemas[this.getObjectName(objectName)];
426
+
427
+ if (component == null || component.properties == null) return ``;
428
+
429
+ console.debug(component.properties);
430
+
431
+ return ``;
432
+ }
433
+
434
+ isEnum(objectName: string) {
435
+ let component = this._swagger.components.schemas[this.getObjectName(objectName)];
436
+ return component.enum != null;
437
+ }
438
+
439
+ isDate(schema: SwaggerSchema) {
440
+ return schema.type == 'string' && schema.format == 'date-time';
441
+ }
442
+
443
+ getObjectName(ref: string) {
444
+ return ref.replace('#/components/schemas/', '');
445
+ }
446
+
447
+ retrieveComponentProperties(swaggerComponent: SwaggerComponent) {
448
+ if (swaggerComponent.properties == null) return [];
449
+
450
+ let properties: PropertyDto[] = [];
451
+ for (let index = 0; index < Object.getOwnPropertyNames(swaggerComponent.properties).length; index++) {
452
+ const propertyName = Object.getOwnPropertyNames(swaggerComponent.properties)[index];
453
+ const required = swaggerComponent.required && swaggerComponent.required.includes(propertyName);
454
+ const type = this.retrieveType(swaggerComponent.properties[propertyName]);
455
+ properties.push({
456
+ ...type,
457
+ name: propertyName,
458
+ nullable: required || type.nullable,
459
+ });
460
+ }
461
+
462
+ return properties;
463
+ }
464
+
465
+ // retrieveSchemaProperties(schema: SwaggerSchema) {
466
+ // if (schema.properties == null) return [];
467
+
468
+ // let properties: PropertyDto[] = [];
469
+ // for (let j = 0; j < Object.getOwnPropertyNames(schema.properties).length; j++) {
470
+ // let propertyName = Object.getOwnPropertyNames(schema.properties)[j];
471
+ // properties +=
472
+ // `
473
+ // ${this.toFirstLetterLowercase(propertyName)}: ${this.retrieveType(schema.properties[propertyName])} | undefined;`
474
+ // }
475
+
476
+ // return properties;
477
+ // }
478
+
479
+ retrieveEnumValues(name: string, swaggerCopmponent: SwaggerComponent) {
480
+ if (swaggerCopmponent.enum == null) return [];
481
+
482
+ let values: EnumValueDto[] = [];
483
+ for (let index = 0; index < swaggerCopmponent.enum.length; index++) {
484
+ try {
485
+ values.push({
486
+ name: swaggerCopmponent.enum[index].split('-')[0].trim(),
487
+ value: swaggerCopmponent.enum[index].split('-')[1].trim(),
488
+ });
489
+ } catch (error) {
490
+ debugger
491
+ }
492
+
493
+ }
494
+
495
+ return values;
496
+ }
497
+
498
+ retrieveNestedObjects(usedTypes: TypeDto[]) {
499
+ for (let i = 0; i < usedTypes.length; i++) {
500
+ const swaggerCopmponent = this._swagger.components.schemas[usedTypes[i].typeName];
501
+ this.retrieveNestedObjectsRecursive(swaggerCopmponent, usedTypes);
502
+ }
503
+ }
504
+
505
+ retrieveNestedObjectsRecursive(swaggerComponent: SwaggerComponent, usedTypes: TypeDto[]) {
506
+ try {
507
+ if (!swaggerComponent.properties) return;
508
+
509
+ for (let j = 0; j < Object.getOwnPropertyNames(swaggerComponent.properties).length; j++) {
510
+ const propertyName = Object.getOwnPropertyNames(swaggerComponent.properties)[j];
511
+
512
+ let nestedUsedType = '';
513
+
514
+ if (!swaggerComponent.properties[propertyName]) continue;
515
+
516
+ if (swaggerComponent.properties[propertyName].$ref) {
517
+ nestedUsedType = swaggerComponent.properties[propertyName].$ref!.replace('#/components/schemas/', '');
518
+ } else if (swaggerComponent.properties[propertyName].allOf && swaggerComponent.properties[propertyName].allOf![0] && swaggerComponent.properties[propertyName].allOf![0]!.$ref) {
519
+ nestedUsedType = swaggerComponent.properties[propertyName].allOf![0]!.$ref!.replace('#/components/schemas/', ''); //TODO Assuming allOf contains a single $ref
520
+ } else if (swaggerComponent.properties[propertyName].type == 'array' && swaggerComponent.properties[propertyName].items?.$ref) {
521
+ nestedUsedType = swaggerComponent.properties[propertyName].items!.$ref!.replace('#/components/schemas/', '');
522
+ }
523
+
524
+ if (nestedUsedType != '' && usedTypes.findIndex(x => x.typeName == nestedUsedType) == -1) {
525
+ let nested = this._swagger.components.schemas[nestedUsedType];
526
+ const required = swaggerComponent.required && swaggerComponent.required.includes(propertyName);
527
+ usedTypes.push({
528
+ typeName: nestedUsedType,
529
+ isTypeReference: nested.type == 'object',
530
+ isNativeType: nested.type != 'object',
531
+ nullable: required,
532
+ isArray: false,
533
+ isVoid: false,
534
+ //potrebbe essere un enum
535
+ });
536
+ this.retrieveNestedObjectsRecursive(nested, usedTypes);
537
+ }
538
+ }
539
+ } catch (error) {
540
+ debugger
541
+ }
542
+ }
543
+
544
+ getNativeType(schema: SwaggerSchema): string {
545
+ let nativeType = 'n.d.';
546
+
547
+ if (schema.$ref != null) {
548
+ debugger
549
+ } else if (schema.type == 'array' && schema.items != null) {
550
+ nativeType = this.getNativeType(schema.items);
551
+ nativeType += '[]';
552
+ } else {
553
+ if (schema.type == 'integer') nativeType = 'integer'; //era number
554
+ if (schema.type == 'string' && schema.format == null) nativeType = 'string';
555
+ if (schema.type == 'string' && schema.format == 'date-time') nativeType = 'dateTime';
556
+ if (schema.type == 'string' && schema.format == 'uuid') nativeType = 'string';
557
+ if (schema.type == 'string' && schema.format == 'binary') nativeType = 'File';
558
+ if (schema.type == 'number') nativeType = 'number';
559
+ if (schema.type == 'boolean') nativeType = 'boolean';
560
+ if (schema.type == 'object') nativeType = 'any';
561
+ }
562
+
563
+ if (nativeType.indexOf('n.d') == -1) {
564
+ return nativeType;
565
+ } else {
566
+ console.error("unmanaged schema type", schema);
567
+ throw new Error("unmanaged schema");
568
+ }
569
+ }
570
+
571
+ getApiNameNormalized(apiName: string) {
572
+ let normalizedApiName = apiName.replace('/api/v{version}/', '').replaceAll('/', '_');
573
+
574
+ if (normalizedApiName.charAt(0) == '_') {
575
+ normalizedApiName = normalizedApiName.slice(1);
576
+ }
577
+ return this.toFirstLetterLowercase(normalizedApiName);
578
+ }
579
+
580
+ toFirstLetterLowercase(value: string) {
581
+ return value.charAt(0).toLowerCase() + value.slice(1);
582
+ }
583
583
  }