@devlearning/swagger-generator 0.0.39 → 1.0.0

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 (54) hide show
  1. package/.vscode/launch.json +8 -2
  2. package/autogeneration/output/api.autogenerated.ts +2144 -5
  3. package/autogeneration/output/model.autogenerated.ts +2789 -0
  4. package/dist/generator-old.js +369 -0
  5. package/dist/generator.js +217 -214
  6. package/dist/generators-writers/angular/api-angular-writer.js +111 -0
  7. package/dist/generators-writers/angular/constants.js +28 -0
  8. package/dist/generators-writers/angular/model-angular-writer.js +42 -0
  9. package/dist/generators-writers/nextjs/api-nextjs-writer.js +127 -0
  10. package/dist/generators-writers/nextjs/constants.js +4 -0
  11. package/dist/generators-writers/nextjs/model-nextjs-writer.js +41 -0
  12. package/dist/generators-writers/utils.js +20 -0
  13. package/dist/index.js +7 -5
  14. package/dist/model.constants.js +1 -4
  15. package/dist/models/api-dto.js +1 -0
  16. package/dist/models/enum-value-dto.js +1 -0
  17. package/dist/models/model-dto.js +1 -0
  18. package/dist/models/parameter-dto.js +1 -0
  19. package/dist/models/property-dto.js +1 -0
  20. package/dist/models/swagger/swagger-component-property.js +1 -0
  21. package/dist/models/swagger/swagger-component.js +1 -0
  22. package/dist/models/swagger/swagger-content.js +1 -0
  23. package/dist/models/swagger/swagger-info.js +1 -0
  24. package/dist/models/swagger/swagger-method.js +1 -0
  25. package/dist/models/swagger/swagger-schema.js +1 -0
  26. package/dist/models/swagger/swagger.js +1 -0
  27. package/dist/models/type-dto.js +1 -0
  28. package/package.json +6 -3
  29. package/src/generator-old.ts +450 -0
  30. package/src/generator.ts +238 -228
  31. package/src/generators-writers/angular/api-angular-writer.ts +139 -0
  32. package/src/generators-writers/angular/constants.ts +36 -0
  33. package/src/generators-writers/angular/model-angular-writer.ts +60 -0
  34. package/src/generators-writers/nextjs/api-nextjs-writer.ts +157 -0
  35. package/src/generators-writers/nextjs/constants.ts +5 -0
  36. package/src/generators-writers/nextjs/model-nextjs-writer.ts +59 -0
  37. package/src/generators-writers/utils.ts +27 -0
  38. package/src/index.ts +7 -5
  39. package/src/model.constants.ts +0 -7
  40. package/src/models/api-dto.ts +17 -0
  41. package/src/models/enum-value-dto.ts +4 -0
  42. package/src/models/model-dto.ts +9 -0
  43. package/src/models/parameter-dto.ts +8 -0
  44. package/src/models/property-dto.ts +5 -0
  45. package/src/models/type-dto.ts +4 -0
  46. package/src/swagger-downloader.ts +1 -1
  47. package/tsconfig.json +1 -1
  48. /package/src/models/{swagger-component-property.ts → swagger/swagger-component-property.ts} +0 -0
  49. /package/src/models/{swagger-component.ts → swagger/swagger-component.ts} +0 -0
  50. /package/src/models/{swagger-content.ts → swagger/swagger-content.ts} +0 -0
  51. /package/src/models/{swagger-info.ts → swagger/swagger-info.ts} +0 -0
  52. /package/src/models/{swagger-method.ts → swagger/swagger-method.ts} +0 -0
  53. /package/src/models/{swagger-schema.ts → swagger/swagger-schema.ts} +0 -0
  54. /package/src/models/{swagger.ts → swagger/swagger.ts} +0 -0
package/dist/generator.js CHANGED
@@ -1,92 +1,97 @@
1
- import fs from 'fs';
2
- import { API_PRE, API_POST } from './api.constants.js';
3
- import { MODEL_POST, MODEL_PRE } from './model.constants.js';
1
+ import { ApiNextJsWriter } from './generators-writers/nextjs/api-nextjs-writer.js';
2
+ import { ApiAngularWriter } from './generators-writers/angular/api-angular-writer.js';
3
+ import { SingleBar, Presets } from 'cli-progress';
4
+ import { ModelNextJsWriter } from './generators-writers/nextjs/model-nextjs-writer.js';
5
+ import { ModelAngularWriter } from './generators-writers/angular/model-angular-writer.js';
4
6
  const contentTypeApplicationJson = 'application/json';
5
7
  const contentTypeMultipartFormData = 'multipart/form-data';
6
8
  export class Generator {
7
9
  _swagger;
8
10
  _outputDirectory;
9
- constructor(swagger, outputDirectory) {
11
+ _outputFormat;
12
+ _dateLibrary;
13
+ _apis = [];
14
+ _models = [];
15
+ _barApis = new SingleBar({
16
+ format: '{bar} {percentage}% | {message} {value}/{total} Elapsed: {duration_formatted}',
17
+ barCompleteChar: '\u2588',
18
+ barIncompleteChar: '\u2591',
19
+ hideCursor: true,
20
+ barsize: 20,
21
+ }, Presets.shades_classic);
22
+ _barModels = new SingleBar({
23
+ format: '{bar} {percentage}% | {message} {value}/{total} Elapsed: {duration_formatted}',
24
+ barCompleteChar: '\u2588',
25
+ barIncompleteChar: '\u2591',
26
+ hideCursor: true,
27
+ barsize: 20,
28
+ }, Presets.shades_classic);
29
+ constructor(swagger, outputDirectory, outputFormat, dateLibrary) {
10
30
  this._swagger = swagger;
11
31
  this._outputDirectory = outputDirectory;
32
+ this._outputFormat = outputFormat;
33
+ this._dateLibrary = dateLibrary;
12
34
  }
13
- generateApi() {
14
- console.debug(`Start autogeneration Apis`);
15
- let apiMethods = ``;
35
+ generate() {
36
+ console.info('%c[Swagger API Generator] %cStarting to parse Swagger JSON file...', 'color: #4CAF50; font-weight: bold;', 'color: #2196F3;');
37
+ this.computeApi();
38
+ this.generateApi();
39
+ this.computeModel();
40
+ this.generateModel();
41
+ console.info('%c[Swagger Generator] %cSwagger file generated successfully!', 'color: #4CAF50; font-weight: bold;', 'color: #00C853;');
42
+ }
43
+ computeApi() {
44
+ this._barApis.start(Object.getOwnPropertyNames(this._swagger.paths).length, 0);
16
45
  for (let index = 0; index < Object.getOwnPropertyNames(this._swagger.paths).length; index++) {
17
46
  const apiName = Object.getOwnPropertyNames(this._swagger.paths)[index];
18
- const swaggerMethod = this._swagger.paths[apiName];
19
- const method = Object.getOwnPropertyNames(swaggerMethod)[0];
20
- const swaggerMethodInfo = swaggerMethod[method];
21
- console.debug(`\tAPI - ${apiName} - ${method}`);
22
- let parametersString = this.retrieveParameters(swaggerMethodInfo, apiName);
23
- let queryParametersDeclaration = this.retrieveQueryParametersDeclaration(swaggerMethodInfo);
24
- let queryParameters = this.retrieveQueryParameters(swaggerMethodInfo);
25
- let returnTypeString = this.retrieveReturnType(swaggerMethodInfo);
26
- if (returnTypeString == null)
27
- returnTypeString = 'void';
28
- let prepareRequestString = ``; //request = this._handleRequest(request);
29
- let haveRequest = swaggerMethodInfo.requestBody != null;
30
- let isMultiPart = haveRequest && swaggerMethodInfo.requestBody.content[contentTypeMultipartFormData] != null;
31
- let httpOptions = 'httpOptions';
32
- if (haveRequest && !isMultiPart) {
33
- prepareRequestString = `const wrappedRequest = this._handleRequest(request);
34
- `;
35
- }
36
- else if (isMultiPart) {
37
- prepareRequestString = `const wrappedRequest = this._handleMultipart(request);
38
- `;
39
- httpOptions = `httpOptionsMultipart`;
40
- }
41
- apiMethods +=
42
- `
43
- public ${this.getApiNameNormalized(apiName)}(${parametersString}): Observable<${returnTypeString}> {
44
- ${queryParametersDeclaration}${prepareRequestString}return this._http.${method}<${returnTypeString}>(\`\${this._baseUrl}${apiName.replace('{version}', '1')}${queryParameters}\`${haveRequest ? ', wrappedRequest' : ''}, ${httpOptions})
45
- .pipe(
46
- map(x => this._handleResponse(x)),
47
- catchError((err, obs) => this._handleError(err, <Observable<any>>obs))
48
- );
49
- }
50
- `;
47
+ this._barApis.update(index, { message: `Elaborando api... ${apiName}` });
48
+ const apiSwaggerMethodKey = this._swagger.paths[apiName];
49
+ const apiMethod = Object.getOwnPropertyNames(apiSwaggerMethodKey)[0];
50
+ const apiSwaggerMethod = apiSwaggerMethodKey[apiMethod];
51
+ // console.debug(`\tAPI - ${apiName} - ${apiMethod}`);
52
+ let apiDto = {
53
+ name: apiName,
54
+ url: apiName.replace('{version}', '1'),
55
+ method: apiMethod,
56
+ parameters: this.computeParameters(apiName, apiSwaggerMethod),
57
+ returnType: this.computeReturnType(apiSwaggerMethod),
58
+ swaggerMethodKey: apiSwaggerMethodKey,
59
+ swaggerMethod: apiSwaggerMethod,
60
+ haveRequest: apiSwaggerMethod.requestBody != null,
61
+ isMultiPart: apiSwaggerMethod.requestBody != null && apiSwaggerMethod.requestBody.content[contentTypeMultipartFormData] != null,
62
+ };
63
+ this._apis.push(apiDto);
51
64
  }
52
- fs.writeFileSync(this._outputDirectory + "/api.autogenerated.ts", `${API_PRE}
53
- ${apiMethods}
54
- ${API_POST}`, { flag: 'w' });
55
65
  }
56
- generateModel() {
66
+ computeModel() {
67
+ this._barModels.start(Object.getOwnPropertyNames(this._swagger.paths).length, 0);
57
68
  let usedTypes = [];
58
69
  let usedMultiPart = [];
59
70
  for (let index = 0; index < Object.getOwnPropertyNames(this._swagger.paths).length; index++) {
60
71
  const apiName = Object.getOwnPropertyNames(this._swagger.paths)[index];
61
- const swaggerMethod = this._swagger.paths[apiName];
62
- const method = Object.getOwnPropertyNames(swaggerMethod)[0];
63
- const swaggerMethodInfo = swaggerMethod[method];
64
- if (apiName == "/api/v{version}/TicketFile/Create") {
65
- debugger;
66
- }
67
- let parametersRefType = swaggerMethodInfo.parameters?.filter(x => x.in == 'query' && x.schema?.$ref != null).map(x => x.schema.$ref.replace('#/components/schemas/', ''));
72
+ const apiSwaggerMethodKey = this._swagger.paths[apiName];
73
+ const apiMethod = Object.getOwnPropertyNames(apiSwaggerMethodKey)[0];
74
+ const apiSwaggerMethod = apiSwaggerMethodKey[apiMethod];
75
+ // if (apiName == "/api/v{version}/TicketFile/Create") {
76
+ // debugger
77
+ // }
78
+ let parametersRefType = apiSwaggerMethod.parameters?.filter(x => x.in == 'query' && x.schema?.$ref != null).map(x => x.schema.$ref.replace('#/components/schemas/', ''));
68
79
  if (parametersRefType) {
69
80
  usedTypes = usedTypes.concat(parametersRefType);
70
- if (swaggerMethodInfo.responses[200].content[contentTypeApplicationJson]?.schema.$ref != null) {
71
- usedTypes.push(swaggerMethodInfo.responses[200].content[contentTypeApplicationJson].schema.$ref.replace('#/components/schemas/', ''));
81
+ this._barModels.update(index, { message: `Elaborando model... ${usedTypes}` });
82
+ if (apiSwaggerMethod.responses[200].content[contentTypeApplicationJson]?.schema.$ref != null) {
83
+ usedTypes.push(apiSwaggerMethod.responses[200].content[contentTypeApplicationJson].schema.$ref.replace('#/components/schemas/', ''));
72
84
  }
73
- if (swaggerMethodInfo.requestBody?.content[contentTypeApplicationJson]?.schema?.$ref) {
74
- usedTypes.push(swaggerMethodInfo.requestBody?.content[contentTypeApplicationJson]?.schema?.$ref.replace('#/components/schemas/', ''));
85
+ if (apiSwaggerMethod.requestBody?.content[contentTypeApplicationJson]?.schema?.$ref) {
86
+ usedTypes.push(apiSwaggerMethod.requestBody?.content[contentTypeApplicationJson]?.schema?.$ref.replace('#/components/schemas/', ''));
75
87
  }
76
- if (swaggerMethodInfo.requestBody?.content[contentTypeMultipartFormData]?.schema != null) {
88
+ if (apiSwaggerMethod.requestBody?.content[contentTypeMultipartFormData]?.schema != null) {
77
89
  usedMultiPart.push(apiName);
78
90
  }
79
91
  }
80
92
  }
81
93
  this.retrieveNestedObjects(usedTypes);
82
94
  usedTypes = [...new Set(usedTypes.map(item => item))]; // [ 'A', 'B']
83
- // usedTypes = usedTypes.filter((value, index, array) => {
84
- // array.indexOf(value) === index;
85
- // });
86
- // usedTypes.forEach(element => {
87
- // console.debug(element);
88
- // });
89
- console.debug(`Start autogeneration Models`);
90
95
  let models = ``;
91
96
  if (this._swagger.components != null
92
97
  && this._swagger.components != undefined
@@ -94,155 +99,156 @@ ${API_POST}`, { flag: 'w' });
94
99
  && this._swagger.components.schemas != undefined) {
95
100
  for (let index = 0; index < Object.getOwnPropertyNames(this._swagger.components.schemas).length; index++) {
96
101
  const modelName = Object.getOwnPropertyNames(this._swagger.components.schemas)[index];
97
- if (modelName == 'ActivatedVoucherSnackListResponse') {
98
- console.debug("ActivatedVoucherSnackListResponse");
99
- }
100
102
  if (usedTypes.indexOf(modelName) < 0) {
101
- console.debug(`\tModel SKIP - ${modelName}`);
103
+ // console.debug(`\tModel SKIP - ${modelName}`);
102
104
  continue;
103
105
  }
104
106
  ;
105
- const swaggerCopmponent = this._swagger.components.schemas[modelName];
106
- console.debug(`\tModel - ${modelName}`);
107
- let type = swaggerCopmponent.type == 'integer' ? 'enum' : 'class';
108
- let content = this.retrieveObjectContent(modelName, swaggerCopmponent);
109
- models +=
110
- `
111
- export ${type} ${modelName} {${content}
112
- }
113
- `;
107
+ const swaggerComponent = this._swagger.components.schemas[modelName];
108
+ // console.debug(`\tModel - ${modelName}`);
109
+ this._models.push({
110
+ modelType: swaggerComponent.type == 'integer' ? 'enum' : 'class',
111
+ name: modelName,
112
+ properties: (swaggerComponent.type == 'object') ? this.retrieveComponentProperties(swaggerComponent) : [],
113
+ enumValues: (swaggerComponent.type == 'integer') ? this.retrieveEnumValues(modelName, swaggerComponent) : [],
114
+ });
114
115
  }
115
116
  }
116
117
  usedMultiPart.forEach(apiName => {
117
118
  const swaggerMethod = this._swagger.paths[apiName];
118
119
  const method = Object.getOwnPropertyNames(swaggerMethod)[0];
119
120
  const swaggerMethodInfo = swaggerMethod[method];
120
- let type = 'class';
121
- let modelName = this.getApiNameNormalized(apiName);
122
- let content = this.retrieveSchemaProperties(swaggerMethodInfo.requestBody.content[contentTypeMultipartFormData].schema);
123
- models +=
124
- `
125
- export ${type} ${modelName} {${content}
126
- }
127
- `;
121
+ this._models.push({
122
+ modelType: 'class',
123
+ name: this.getApiNameNormalized(apiName),
124
+ properties: this.retrieveComponentProperties(swaggerMethodInfo.requestBody.content[contentTypeMultipartFormData].schema),
125
+ enumValues: [],
126
+ });
128
127
  });
129
- fs.writeFileSync(this._outputDirectory + "/model.autogenerated.ts", `${MODEL_PRE}
130
- ${models}
131
- ${MODEL_POST}`, { flag: 'w' });
132
128
  }
133
- retrieveParameters(swaggerMethodInfo, apiName) {
134
- if (swaggerMethodInfo.requestBody != null && swaggerMethodInfo.requestBody.content[contentTypeMultipartFormData] != null) {
135
- var modelName = this.getApiNameNormalized(apiName);
136
- return `request: Models.${modelName}`;
129
+ generateApi() {
130
+ this._barApis.update(this._apis.length, { message: `Inizio scrittura api...` });
131
+ if (this._outputFormat == 'angular') {
132
+ const apiWriter = new ApiAngularWriter(this._outputDirectory);
133
+ apiWriter.write(this._apis);
137
134
  }
138
- else {
139
- if (swaggerMethodInfo.requestBody != null) {
140
- return `request: Models.${swaggerMethodInfo.requestBody.content[contentTypeApplicationJson].schema.$ref.replace('#/components/schemas/', '')}`;
141
- }
142
- let parameters = ``;
143
- swaggerMethodInfo.parameters?.filter(x => x.in == 'query').forEach(parameter => {
144
- if (parameter.schema.$ref != null) {
145
- parameters += `${this.toFirstLetterLowercase(parameter.name)}: Models.${parameter.schema.$ref.replace('#/components/schemas/', '')}, `;
146
- }
147
- else {
148
- const nativeType = this.getNativeType(parameter.schema);
149
- const nullable = !parameter.required ? '?' : '';
150
- parameters += `${this.toFirstLetterLowercase(parameter.name)}${nullable}: ${nativeType}, `;
151
- }
152
- });
153
- if (parameters.length > 2)
154
- parameters = parameters.substring(0, parameters.length - 2);
155
- return parameters;
135
+ else if (this._outputFormat == 'next') {
136
+ const apiWriter = new ApiNextJsWriter(this._outputDirectory);
137
+ apiWriter.write(this._apis);
156
138
  }
139
+ this._barApis.update(this._apis.length, { message: `Scrittura api completata` });
140
+ this._barApis.stop();
157
141
  }
158
- retrieveQueryParametersDeclaration(swaggerMethodInfo) {
159
- if (swaggerMethodInfo.requestBody != null)
160
- return ``;
161
- let filteredParameters = swaggerMethodInfo.parameters?.filter(x => x.in == 'query');
162
- if (filteredParameters == null || filteredParameters == undefined || filteredParameters.length == 0)
163
- return ``;
164
- let parameters = ``;
165
- filteredParameters.forEach(parameter => {
166
- if (parameter.schema.$ref != null) {
167
- if (this.isEnum(parameter.schema.$ref) != null) {
168
- parameters += this.retrieveQueryParametersDeclarationStatement(parameter);
169
- }
170
- else {
171
- throw new Error("retrieveQueryParameters unmanaged parameter.schema.$ref");
172
- }
173
- }
174
- else {
175
- parameters += this.retrieveQueryParametersDeclarationStatement(parameter);
176
- }
177
- });
178
- // if (parameters.length > 2)
179
- // parameters = parameters.substring(0, parameters.length - 1);
180
- return parameters;
142
+ generateModel() {
143
+ this._barModels.update(this._apis.length, { message: `Inizio scrittura model...` });
144
+ if (this._outputFormat == 'angular') {
145
+ const apiWriter = new ModelAngularWriter(this._outputDirectory);
146
+ apiWriter.write(this._models);
147
+ }
148
+ else if (this._outputFormat == 'next') {
149
+ const apiWriter = new ModelNextJsWriter(this._outputDirectory);
150
+ apiWriter.write(this._models);
151
+ }
152
+ this._barModels.update(this._apis.length, { message: `Scrittura model completata` });
153
+ this._barModels.stop();
181
154
  }
182
- retrieveQueryParametersDeclarationStatement(parameter) {
183
- let paramName = this.toFirstLetterLowercase(parameter.name);
184
- if (!parameter.required) {
185
- if (this.isDate(parameter.schema)) {
186
- return `let ${paramName}Param: string = ${paramName} != null && ${paramName} != undefined && ${paramName}.isValid() ? encodeURIComponent(this._momentToString(${paramName})) : '';
187
- `;
188
- }
189
- else {
190
- return `let ${paramName}Param: string = ${paramName} != null && ${paramName} != undefined ? encodeURIComponent('' + ${paramName}) : '';
191
- `;
192
- }
155
+ computeParameters(apiName, swaggerMethod) {
156
+ if (!apiName)
157
+ return [];
158
+ if (!swaggerMethod || swaggerMethod == null)
159
+ return [];
160
+ let parameters = [];
161
+ if (swaggerMethod.requestBody != null && swaggerMethod.requestBody.content[contentTypeMultipartFormData] != null) {
162
+ var modelName = this.getApiNameNormalized(apiName);
163
+ parameters.push({
164
+ name: 'request',
165
+ typeName: modelName,
166
+ nullable: false,
167
+ isQuery: false,
168
+ isEnum: false,
169
+ });
193
170
  }
194
171
  else {
195
- if (this.isDate(parameter.schema)) {
196
- return `let ${paramName}Param: string = encodeURIComponent(this._momentToString(${paramName}));
197
- `;
172
+ if (swaggerMethod.requestBody != null) {
173
+ parameters.push({
174
+ name: 'request',
175
+ typeName: swaggerMethod.requestBody.content[contentTypeApplicationJson].schema.$ref.replace('#/components/schemas/', ''),
176
+ nullable: false,
177
+ isQuery: false,
178
+ isEnum: false,
179
+ });
198
180
  }
199
181
  else {
200
- return `let ${paramName}Param: string = encodeURIComponent('' + ${paramName});
201
- `;
182
+ swaggerMethod.parameters?.filter(x => x.in == 'query').forEach(parameter => {
183
+ if (parameter.schema.$ref != null) {
184
+ parameters.push({
185
+ name: this.toFirstLetterLowercase(parameter.name),
186
+ typeName: parameter.schema.$ref.replace('#/components/schemas/', ''),
187
+ nullable: !parameter.required,
188
+ swaggerParameter: parameter,
189
+ isQuery: true,
190
+ isEnum: this.isEnum(parameter.schema.$ref),
191
+ });
192
+ }
193
+ else {
194
+ parameters.push({
195
+ name: this.toFirstLetterLowercase(parameter.name),
196
+ typeName: this.getNativeType(parameter.schema),
197
+ nullable: !parameter.required,
198
+ swaggerParameter: parameter,
199
+ isQuery: true,
200
+ isEnum: false,
201
+ });
202
+ }
203
+ });
202
204
  }
203
205
  }
204
- }
205
- retrieveQueryParameters(swaggerMethodInfo) {
206
- if (swaggerMethodInfo.requestBody != null)
207
- return ``;
208
- let filteredParameters = swaggerMethodInfo.parameters?.filter(x => x.in == 'query');
209
- if (filteredParameters == null || filteredParameters == undefined || filteredParameters.length == 0)
210
- return ``;
211
- let parameters = `?`;
212
- filteredParameters.forEach(parameter => {
213
- if (parameter.schema.$ref != null) {
214
- if (this.isEnum(parameter.schema.$ref) != null) {
215
- parameters += `${this.toFirstLetterLowercase(parameter.name)}=\${` + this.toFirstLetterLowercase(parameter.name) + `Param}&`;
216
- ;
217
- }
218
- else {
219
- throw new Error("retrieveQueryParameters unmanaged parameter.schema.$ref");
220
- }
221
- }
222
- else {
223
- parameters += `${this.toFirstLetterLowercase(parameter.name)}=\${` + this.toFirstLetterLowercase(parameter.name) + `Param}&`;
224
- }
225
- });
226
- if (parameters.length > 1)
227
- parameters = parameters.substring(0, parameters.length - 1);
228
206
  return parameters;
229
207
  }
230
- retrieveReturnType(swaggerMethodInfo) {
231
- if (swaggerMethodInfo.responses[200] == null)
232
- return 'void';
208
+ computeReturnType(swaggerMethod) {
209
+ if (swaggerMethod.responses[200] == null) {
210
+ return {
211
+ typeName: 'void',
212
+ nullable: false,
213
+ };
214
+ }
233
215
  try {
234
- if (swaggerMethodInfo.responses[200].content[contentTypeApplicationJson].schema.$ref != null)
235
- return `Models.${this.getObjectName(swaggerMethodInfo.responses[200]?.content[contentTypeApplicationJson].schema.$ref)}`;
216
+ if (swaggerMethod.responses[200].content[contentTypeApplicationJson].schema.$ref != null)
217
+ return {
218
+ typeName: this.getObjectName(swaggerMethod.responses[200]?.content[contentTypeApplicationJson].schema.$ref),
219
+ nullable: false,
220
+ };
236
221
  }
237
222
  catch (error) {
238
223
  const errorMessage = "\t\tAttenzione forse hai dimenticato IActionResult e non hai tipizzato il tipo restituito dal servizio";
239
224
  console.error(`%c${errorMessage}`, 'color: red');
240
225
  throw new Error(errorMessage);
241
226
  }
242
- if (swaggerMethodInfo.responses[200]?.content[contentTypeApplicationJson].schema.type != null)
243
- return this.getNativeType(swaggerMethodInfo.responses[200]?.content[contentTypeApplicationJson].schema);
244
- console.error("unmanaged swaggerMethodInfo", swaggerMethodInfo);
245
- throw new Error("unmanaged swaggerMethodInfo");
227
+ if (swaggerMethod.responses[200]?.content[contentTypeApplicationJson].schema.type != null) {
228
+ let schema = swaggerMethod.responses[200]?.content[contentTypeApplicationJson].schema;
229
+ if (schema.type == 'array') {
230
+ if (schema.items.$ref != null) {
231
+ return {
232
+ typeName: `${this.getObjectName(schema.items.$ref)}[]`,
233
+ nullable: false,
234
+ };
235
+ }
236
+ }
237
+ else {
238
+ return {
239
+ typeName: this.getNativeType(swaggerMethod.responses[200]?.content[contentTypeApplicationJson].schema),
240
+ nullable: false,
241
+ };
242
+ }
243
+ // if (swaggerComponentProperty.items.$ref != null)
244
+ // return `${this.getObjectName(swaggerComponentProperty.items.$ref)}[]`;
245
+ }
246
+ else {
247
+ return {
248
+ typeName: this.getNativeType(swaggerMethod.responses[200]?.content[contentTypeApplicationJson].schema),
249
+ nullable: false,
250
+ };
251
+ }
246
252
  }
247
253
  retrieveType(swaggerComponentProperty) {
248
254
  if (swaggerComponentProperty.$ref != null)
@@ -276,48 +282,42 @@ ${MODEL_POST}`, { flag: 'w' });
276
282
  getObjectName(ref) {
277
283
  return ref.replace('#/components/schemas/', '');
278
284
  }
279
- retrieveObjectContent(name, swaggerComponent) {
280
- if (swaggerComponent.type == 'object')
281
- return this.retrieveComponentProperties(swaggerComponent);
282
- else if (swaggerComponent.type == 'integer')
283
- return this.retrieveEnumValues(name, swaggerComponent);
284
- }
285
285
  retrieveComponentProperties(swaggerCopmponent) {
286
286
  if (swaggerCopmponent.properties == null)
287
- return ``;
288
- let properties = ``;
287
+ return [];
288
+ let properties = [];
289
289
  for (let index = 0; index < Object.getOwnPropertyNames(swaggerCopmponent.properties).length; index++) {
290
290
  const propertyName = Object.getOwnPropertyNames(swaggerCopmponent.properties)[index];
291
- properties +=
292
- `
293
- ${propertyName}: ${this.retrieveType(swaggerCopmponent.properties[propertyName])} | undefined;`;
294
- }
295
- return properties;
296
- }
297
- retrieveSchemaProperties(schema) {
298
- if (schema.properties == null)
299
- return ``;
300
- let properties = ``;
301
- for (let j = 0; j < Object.getOwnPropertyNames(schema.properties).length; j++) {
302
- let propertyName = Object.getOwnPropertyNames(schema.properties)[j];
303
- properties +=
304
- `
305
- ${this.toFirstLetterLowercase(propertyName)}: ${this.retrieveType(schema.properties[propertyName])} | undefined;`;
291
+ properties.push({
292
+ name: propertyName,
293
+ typeName: this.retrieveType(swaggerCopmponent.properties[propertyName]),
294
+ nullable: true,
295
+ });
306
296
  }
307
297
  return properties;
308
298
  }
299
+ // retrieveSchemaProperties(schema: SwaggerSchema) {
300
+ // if (schema.properties == null) return [];
301
+ // let properties: PropertyDto[] = [];
302
+ // for (let j = 0; j < Object.getOwnPropertyNames(schema.properties).length; j++) {
303
+ // let propertyName = Object.getOwnPropertyNames(schema.properties)[j];
304
+ // properties +=
305
+ // `
306
+ // ${this.toFirstLetterLowercase(propertyName)}: ${this.retrieveType(schema.properties[propertyName])} | undefined;`
307
+ // }
308
+ // return properties;
309
+ // }
309
310
  retrieveEnumValues(name, swaggerCopmponent) {
310
311
  if (swaggerCopmponent.enum == null)
311
- return ``;
312
- let properties = ``;
312
+ return [];
313
+ let values = [];
313
314
  for (let index = 0; index < swaggerCopmponent.enum.length; index++) {
314
- const name = swaggerCopmponent.enum[index].split('-')[0].trim();
315
- const value = swaggerCopmponent.enum[index].split('-')[1].trim();
316
- properties +=
317
- `
318
- ${name} = ${value},`;
315
+ values.push({
316
+ name: swaggerCopmponent.enum[index].split('-')[0].trim(),
317
+ value: swaggerCopmponent.enum[index].split('-')[1].trim(),
318
+ });
319
319
  }
320
- return properties;
320
+ return values;
321
321
  }
322
322
  retrieveNestedObjects(usedTypes) {
323
323
  for (let i = 0; i < usedTypes.length; i++) {
@@ -348,7 +348,10 @@ ${MODEL_POST}`, { flag: 'w' });
348
348
  }
349
349
  getNativeType(schema) {
350
350
  let nativeType = 'n.d.';
351
- if (schema.type == 'array') {
351
+ if (schema.$ref != null) {
352
+ debugger;
353
+ }
354
+ else if (schema.type == 'array') {
352
355
  nativeType = this.getNativeType(schema.items);
353
356
  nativeType += '[]';
354
357
  }
@@ -358,7 +361,7 @@ ${MODEL_POST}`, { flag: 'w' });
358
361
  if (schema.type == 'string' && schema.format == null)
359
362
  nativeType = 'string';
360
363
  if (schema.type == 'string' && schema.format == 'date-time')
361
- nativeType = 'moment.Moment';
364
+ nativeType = this._dateLibrary == 'moment' ? 'moment.Moment' : 'Date';
362
365
  if (schema.type == 'string' && schema.format == 'uuid')
363
366
  nativeType = 'string';
364
367
  if (schema.type == 'string' && schema.format == 'binary')
@@ -0,0 +1,111 @@
1
+ import fs from 'fs';
2
+ import { API_POST, API_PRE } from './constants.js';
3
+ import { Utils } from '../utils.js';
4
+ export class ApiAngularWriter {
5
+ _outputDirectory;
6
+ constructor(_outputDirectory) {
7
+ this._outputDirectory = _outputDirectory;
8
+ }
9
+ write(apis) {
10
+ let apiString = '';
11
+ apis.forEach(api => {
12
+ apiString += this._apiString(api);
13
+ });
14
+ this._writeFile(apiString);
15
+ }
16
+ _apiString(api) {
17
+ let apiNameNormalized = Utils.getApiNameNormalized(api.name);
18
+ let parametersString = this._parameters(api);
19
+ let queryParametersPreparation = this._queryParametersPreparation(api);
20
+ let requestPreparation = this._requestPreparation(api);
21
+ let queryParameters = this._queryParameters(api);
22
+ let returnTypeString = this._returnType(api);
23
+ let haveRequest = api.haveRequest;
24
+ let method = api.method.toLowerCase();
25
+ let httpOptions = api.isMultiPart ? 'httpOptionsMultiPart' : 'httpOptions';
26
+ let apiString = `
27
+ public ${apiNameNormalized}(${parametersString}): Observable<${returnTypeString}> {
28
+ ${queryParametersPreparation}${requestPreparation}return this._http.${method}<${returnTypeString}>(\`\${this._baseUrl}${api.url}${queryParameters}\`${haveRequest ? ', wrappedRequest' : ''}, ${httpOptions})
29
+ .pipe(
30
+ map(x => this._handleResponse(x)),
31
+ catchError((err, obs) => this._handleError(err, <Observable<any>>obs))
32
+ );
33
+ }
34
+ `;
35
+ return apiString;
36
+ }
37
+ _parameters(api) {
38
+ let parametersString = '';
39
+ api.parameters.forEach(parameter => {
40
+ parametersString += `${parameter.name}${parameter.nullable ? '?' : ''}: ${parameter.typeName}, `;
41
+ });
42
+ if (api.parameters.length > 0)
43
+ parametersString = parametersString.substring(0, parametersString.length - 2);
44
+ return parametersString;
45
+ }
46
+ _returnType(api) {
47
+ return api.returnType ? api.returnType.typeName : 'any';
48
+ }
49
+ _queryParametersPreparation(api) {
50
+ let queryParametersPreparation = '';
51
+ api.parameters.forEach(parameter => {
52
+ if (parameter.isQuery) {
53
+ queryParametersPreparation += this._queryParametersPreparationStatement(parameter);
54
+ }
55
+ });
56
+ return queryParametersPreparation;
57
+ }
58
+ _queryParametersPreparationStatement(parameter) {
59
+ if (parameter.nullable) {
60
+ if (Utils.isDate(parameter.swaggerParameter?.schema)) {
61
+ return `let ${parameter.name}Param: string = ${parameter.name} != null && ${parameter.name} != undefined && ${parameter.name}.isValid() ? encodeURIComponent(this._momentToString(${parameter.name})) : '';
62
+ `;
63
+ }
64
+ else {
65
+ return `let ${parameter.name}Param: string = ${parameter.name} != null && ${parameter.name} != undefined ? encodeURIComponent('' + ${parameter.name}) : '';
66
+ `;
67
+ }
68
+ }
69
+ else {
70
+ if (Utils.isDate(parameter.swaggerParameter?.schema)) {
71
+ return `let ${parameter.name}Param: string = encodeURIComponent(this._momentToString(${parameter.name}));
72
+ `;
73
+ }
74
+ else {
75
+ return `let ${parameter.name}Param: string = encodeURIComponent('' + ${parameter.name});
76
+ `;
77
+ }
78
+ }
79
+ }
80
+ _queryParameters(api) {
81
+ let queryParameters = '';
82
+ api.parameters.forEach(parameter => {
83
+ if (parameter.isQuery) {
84
+ queryParameters += this._queryParametersStatement(parameter);
85
+ }
86
+ });
87
+ if (queryParameters.length > 0) {
88
+ queryParameters = '?' + queryParameters.substring(0, queryParameters.length - 1);
89
+ }
90
+ return queryParameters;
91
+ }
92
+ _queryParametersStatement(parameter) {
93
+ if (parameter.swaggerParameter == null)
94
+ return '';
95
+ if (!parameter.isQuery)
96
+ return '';
97
+ return `${parameter.name}=\${${parameter.name}Param}&`;
98
+ }
99
+ _requestPreparation(api) {
100
+ if (!api.haveRequest) {
101
+ return '';
102
+ }
103
+ return `let wrappedRequest = this._handleRequest(request);
104
+ `;
105
+ }
106
+ _writeFile(apis) {
107
+ fs.writeFileSync(this._outputDirectory + "/api.autogenerated.ts", `${API_PRE}
108
+ ${apis}
109
+ ${API_POST}`, { flag: 'w' });
110
+ }
111
+ }