@devlearning/swagger-generator 0.0.8 → 0.0.10

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.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import fs from 'fs';
2
+ import { Generator } from './generator.js';
3
3
  import { SwaggerDownloader } from './swagger-downloader.js';
4
4
  var args = process.argv.slice(2);
5
5
  if (args.length !== 2) {
@@ -13,308 +13,10 @@ const outputDirectory = args[1];
13
13
  // const apiUrl = args[0]//"http://localhost:5208";
14
14
  // const version = args[1]; //"1";
15
15
  // const swaggerJsonUrl = `${apiUrl}/swagger/v${version}/swagger.json`;
16
- const contentType = 'application/json';
17
- export class Generator {
18
- _swagger;
19
- constructor(swagger) {
20
- this._swagger = swagger;
21
- }
22
- generateApi() {
23
- console.debug(`Start autogeneration Apis`);
24
- let apiMethods = ``;
25
- for (let index = 0; index < Object.getOwnPropertyNames(this._swagger.paths).length; index++) {
26
- const apiName = Object.getOwnPropertyNames(this._swagger.paths)[index];
27
- const swaggerMethod = this._swagger.paths[apiName];
28
- const method = Object.getOwnPropertyNames(swaggerMethod)[0];
29
- const swaggerMethodInfo = swaggerMethod[method];
30
- console.debug(`\tAPI - ${apiName} - ${method}`);
31
- let parametersString = this.retrieveParameters(swaggerMethodInfo);
32
- let queryParameters = this.retrieveQueryParameters(swaggerMethodInfo);
33
- let returnTypeString = this.retrieveReturnType(swaggerMethodInfo);
34
- if (returnTypeString == null)
35
- returnTypeString = 'void';
36
- let prepareRequestString = ``; //request = this._handleRequest(request);
37
- let haveRequest = swaggerMethodInfo.requestBody != null;
38
- if (haveRequest) {
39
- prepareRequestString = `request = this._handleRequest(request);
40
- `;
41
- }
42
- apiMethods +=
43
- `
44
- public ${apiName.replace('/api/v{version}/', '').replaceAll('/', '_')}(${parametersString}): Observable<${returnTypeString}>{
45
- ${prepareRequestString}return this._http.${method}<${returnTypeString}>(\`\${environment.BASE_URL}${apiName.replace('{version}', '1')}${queryParameters}\`${haveRequest ? ', request' : ''}, httpOptions)
46
- .pipe(
47
- map(x => this._handleResponse(x)),
48
- catchError((err, obs) => {
49
- return this._handleError(err, <Observable<any>>obs);
50
- })
51
- );
52
- }
53
- `;
54
- }
55
- fs.writeFileSync(outputDirectory + "/api.autogenerated.ts", `${apiPre}
56
- ${apiMethods}
57
- ${apiPost}`, { flag: 'w' });
58
- }
59
- generateModel() {
60
- let usedTypes = [];
61
- for (let index = 0; index < Object.getOwnPropertyNames(this._swagger.paths).length; index++) {
62
- const apiName = Object.getOwnPropertyNames(this._swagger.paths)[index];
63
- const swaggerMethod = this._swagger.paths[apiName];
64
- const method = Object.getOwnPropertyNames(swaggerMethod)[0];
65
- const swaggerMethodInfo = swaggerMethod[method];
66
- // if(apiName == "/api/v{version}/Ticket/Create"){
67
- // debugger
68
- // }
69
- let parametersRefType = swaggerMethodInfo.parameters.filter(x => x.in == 'query' && x.schema?.$ref != null).map(x => x.schema.$ref.replace('#/components/schemas/', ''));
70
- usedTypes = usedTypes.concat(parametersRefType);
71
- if (swaggerMethodInfo.responses[200].content[contentType].schema.$ref != null) {
72
- usedTypes.push(swaggerMethodInfo.responses[200].content[contentType].schema.$ref.replace('#/components/schemas/', ''));
73
- }
74
- if (swaggerMethodInfo.requestBody?.content[contentType]?.schema?.$ref) {
75
- usedTypes.push(swaggerMethodInfo.requestBody?.content[contentType]?.schema?.$ref.replace('#/components/schemas/', ''));
76
- }
77
- }
78
- this.retrieveNestedObjects(usedTypes);
79
- usedTypes = [...new Set(usedTypes.map(item => item))]; // [ 'A', 'B']
80
- // usedTypes = usedTypes.filter((value, index, array) => {
81
- // array.indexOf(value) === index;
82
- // });
83
- // usedTypes.forEach(element => {
84
- // console.debug(element);
85
- // });
86
- console.debug(`Start autogeneration Models`);
87
- let models = ``;
88
- for (let index = 0; index < Object.getOwnPropertyNames(this._swagger.components.schemas).length; index++) {
89
- const modelName = Object.getOwnPropertyNames(this._swagger.components.schemas)[index];
90
- if (modelName == 'ActivatedVoucherSnackListResponse') {
91
- console.debug("ActivatedVoucherSnackListResponse");
92
- }
93
- if (usedTypes.indexOf(modelName) < 0) {
94
- console.debug(`\tModel SKIP - ${modelName}`);
95
- continue;
96
- }
97
- ;
98
- const swaggerCopmponent = this._swagger.components.schemas[modelName];
99
- console.debug(`\tModel - ${modelName}`);
100
- let type = swaggerCopmponent.type == 'integer' ? 'enum' : 'class';
101
- let content = this.retrieveObjectContent(modelName, swaggerCopmponent);
102
- models +=
103
- `
104
- export ${type} ${modelName} {${content}
105
- }
106
- `;
107
- }
108
- fs.writeFileSync(outputDirectory + "/model.autogenerated.ts", `${modelPre}
109
- ${models}
110
- ${modelPost}`, { flag: 'w' });
111
- }
112
- retrieveParameters(swaggerMethodInfo) {
113
- if (swaggerMethodInfo.requestBody != null) {
114
- return `request: ${swaggerMethodInfo.requestBody.content[contentType].schema.$ref.replace('#/components/schemas/', '')}`;
115
- }
116
- let parameters = ``;
117
- swaggerMethodInfo.parameters.filter(x => x.in == 'query').forEach(parameter => {
118
- if (parameter.schema.$ref != null) {
119
- parameters += `${parameter.name}: ${parameter.schema.$ref.replace('#/components/schemas/', '')}, `;
120
- }
121
- else {
122
- parameters += `${parameter.name}: ${this.getNativeType(parameter.schema)}, `;
123
- }
124
- });
125
- if (parameters.length > 2)
126
- parameters = parameters.substring(0, parameters.length - 2);
127
- return parameters;
128
- }
129
- retrieveQueryParameters(swaggerMethodInfo) {
130
- if (swaggerMethodInfo.requestBody != null)
131
- return ``;
132
- let filteredParameters = swaggerMethodInfo.parameters.filter(x => x.in == 'query');
133
- if (filteredParameters.length == 0)
134
- return ``;
135
- let parameters = `?`;
136
- filteredParameters.forEach(parameter => {
137
- if (parameter.schema.$ref != null) {
138
- this.parametrizeObject(parameter.schema.$ref);
139
- //parameters += `${parameter.name}: ${parameter.schema.$ref.replace('#/components/schemas/', '')}&`;
140
- }
141
- else {
142
- parameters += `${this.lowercaseFirstLetter(parameter.name)}=\${` + this.lowercaseFirstLetter(parameter.name) + `}&`;
143
- }
144
- });
145
- if (parameters.length > 1)
146
- parameters = parameters.substring(0, parameters.length - 1);
147
- return parameters;
148
- }
149
- retrieveReturnType(swaggerMethodInfo) {
150
- if (swaggerMethodInfo.responses[200] == null)
151
- return 'void';
152
- if (swaggerMethodInfo.responses[200].content[contentType].schema.$ref != null)
153
- return swaggerMethodInfo.responses[200]?.content[contentType].schema.$ref.replace('#/components/schemas/', '');
154
- if (swaggerMethodInfo.responses[200]?.content[contentType].schema.type != null)
155
- return this.getNativeType(swaggerMethodInfo.responses[200]?.content[contentType].schema);
156
- console.error("unmanaged swaggerMethodInfo", swaggerMethodInfo);
157
- throw new Error("unmanaged swaggerMethodInfo");
158
- }
159
- retrieveType(swaggerComponentProperty) {
160
- if (swaggerComponentProperty.$ref != null)
161
- return swaggerComponentProperty.$ref.replace('#/components/schemas/', '');
162
- if (swaggerComponentProperty.type != null && swaggerComponentProperty.type == 'array')
163
- if (swaggerComponentProperty.items.$ref != null)
164
- return swaggerComponentProperty.items.$ref.replace('#/components/schemas/', '');
165
- else
166
- return this.getNativeType(swaggerComponentProperty);
167
- if (swaggerComponentProperty.type != null)
168
- return this.getNativeType(swaggerComponentProperty);
169
- if (swaggerComponentProperty.type == null)
170
- return '';
171
- console.error("unmanaged swaggerMethodInfo", swaggerComponentProperty);
172
- throw new Error("unmanaged swaggerMethodInfo");
173
- }
174
- parametrizeObject(objectName) {
175
- let component = this._swagger.components.schemas[objectName.replace('#/components/schemas/', '')];
176
- if (component == null || component.properties == null)
177
- return ``;
178
- console.debug(component.properties);
179
- return ``;
180
- }
181
- retrieveObjectContent(name, swaggerComponent) {
182
- if (swaggerComponent.type == 'object')
183
- return this.retrieveObjectProperties(swaggerComponent);
184
- else if (swaggerComponent.type == 'integer')
185
- return this.retrieveEnumValues(name, swaggerComponent);
186
- }
187
- retrieveObjectProperties(swaggerCopmponent) {
188
- if (swaggerCopmponent.properties == null)
189
- return ``;
190
- // console.debug(`\t\t${Object.getOwnPropertyNames(swaggerCopmponent.properties).length}`);
191
- let properties = ``;
192
- for (let index = 0; index < Object.getOwnPropertyNames(swaggerCopmponent.properties).length; index++) {
193
- const propertyName = Object.getOwnPropertyNames(swaggerCopmponent.properties)[index];
194
- properties +=
195
- `
196
- ${propertyName}: ${this.retrieveType(swaggerCopmponent.properties[propertyName])} | undefined;`;
197
- }
198
- return properties;
199
- }
200
- retrieveEnumValues(name, swaggerCopmponent) {
201
- if (swaggerCopmponent.enum == null)
202
- return ``;
203
- let properties = ``;
204
- for (let index = 0; index < swaggerCopmponent.enum.length; index++) {
205
- const name = swaggerCopmponent.enum[index].split('-')[0].trim();
206
- const value = swaggerCopmponent.enum[index].split('-')[1].trim();
207
- properties +=
208
- `
209
- ${name} = ${value},`;
210
- }
211
- return properties;
212
- }
213
- retrieveNestedObjects(usedTypes) {
214
- for (let i = 0; i < usedTypes.length; i++) {
215
- const swaggerCopmponent = this._swagger.components.schemas[usedTypes[i]];
216
- // const name = usedTypes[i]
217
- // const modelName = <string>Object.getOwnPropertyNames(this._swagger.components.schemas)[name];
218
- this.retrieveNestedObjects2(swaggerCopmponent, usedTypes);
219
- }
220
- }
221
- /*
222
- "ActivatedVoucherSnackReadQueryResponse": {
223
- "type": "object",
224
- "properties": {
225
- "list": {
226
- "type": "array",
227
- "items": {
228
- "$ref": "#/components/schemas/ActivatedVoucherSnackListResponse"
229
- },
230
- "nullable": true
231
- }
232
- },
233
- "additionalProperties": false
234
- },
235
- */
236
- retrieveNestedObjects2(swaggerComponent, usedTypes) {
237
- if (!swaggerComponent.properties)
238
- return;
239
- for (let j = 0; j < Object.getOwnPropertyNames(swaggerComponent.properties).length; j++) {
240
- const propertyName = Object.getOwnPropertyNames(swaggerComponent.properties)[j];
241
- let nestedUsedType = '';
242
- if (swaggerComponent.properties[propertyName].$ref != null) {
243
- nestedUsedType = swaggerComponent.properties[propertyName].$ref.replace('#/components/schemas/', '');
244
- }
245
- else if (swaggerComponent.properties[propertyName].type == 'array' && swaggerComponent.properties[propertyName].items.$ref != null) {
246
- nestedUsedType = swaggerComponent.properties[propertyName].items.$ref.replace('#/components/schemas/', '');
247
- }
248
- if (nestedUsedType != '' && usedTypes.findIndex(x => x == nestedUsedType) == -1) {
249
- usedTypes.push(nestedUsedType);
250
- let nested = this._swagger.components.schemas[nestedUsedType];
251
- this.retrieveNestedObjects2(nested, usedTypes);
252
- }
253
- }
254
- }
255
- getNativeType(schema) {
256
- if (schema.type == 'integer')
257
- return 'number';
258
- if (schema.type == 'string' && schema.format == null)
259
- return 'string';
260
- if (schema.type == 'string' && schema.format == 'date-time')
261
- return 'moment.Moment';
262
- if (schema.type == 'string' && schema.format == 'uuid')
263
- return 'string';
264
- if (schema.type == 'number')
265
- return 'number';
266
- if (schema.type == 'array')
267
- return '[]';
268
- if (schema.type == 'boolean')
269
- return 'boolean';
270
- if (schema.type == 'object')
271
- return 'any';
272
- console.error("unmanaged schema type", schema);
273
- throw new Error("unmanaged schema");
274
- }
275
- lowercaseFirstLetter(value) {
276
- return value.charAt(0).toLowerCase() + value.slice(1);
277
- }
278
- }
279
16
  const swaggerDownloader = new SwaggerDownloader();
280
- const apiPre = `import { HttpClient } from '@angular/common/http';
281
- import { Injectable } from '@angular/core';
282
- import { Observable, catchError, map } from 'rxjs';
283
- import { httpOptions } from 'src/app/core/utils/http-options';
284
- import { DatiUtenteTestataResponse } from '../models/dati-utente-testata-response';
285
- import { LanguageCultureListQueryResponse } from '../models/language-culture';
286
- import { API_AIRLINE_COMPANY, API_LANGUAGE_CULTURE, API_TEST, API_USER, API_VOUCHER_SNACK } from '../utils/constants';
287
- import { ApiBase } from './../utils/api-base';
288
- import { DialogMessageService } from './dialog-message.service';
289
- import * as moment from 'moment-timezone';
290
- import { VoucherSnackResponse } from '../models/api/voucher-snack-response.models';
291
- import { VoucherSnackRequest } from '../models/api/voucher-snack-request.models';
292
- import { ActivatedSnackVoucherResponse, SnackType } from 'src/app/ticket/models/richiesta-servizio-snack.models';
293
- import { VoucherSnackRequestEmission } from '../models/api/voucher-snack-request-emission';
294
- import { ActivateSnackVoucherResponse } from '../models/api/activate-snack-voucher-response.models';
295
- import { VoucherActivationRequest } from '../models/api/voucher-activation-request.model';
296
- import { Utente } from '../models/utente';
297
- import { AirlineCompany } from 'src/app/sharedmodules/dialog-compagnie-aeree/compagnia-aerea.model';
298
-
299
- @Injectable({
300
- providedIn: 'root',
301
- })
302
- export class ApiService extends ApiBase {
303
- constructor(
304
- private _http: HttpClient,
305
- _dialogMessage: DialogMessageService
306
- ) {
307
- super(_dialogMessage);
308
- }
309
- `;
310
- const apiPost = `}`;
311
- const modelPre = `import * as moment from 'moment';
312
- `;
313
- const modelPost = `
314
- `;
315
17
  swaggerDownloader.download(new URL(swaggerJsonUrl))
316
18
  .then(swaggerDoc => {
317
- return new Generator(swaggerDoc);
19
+ return new Generator(swaggerDoc, outputDirectory);
318
20
  })
319
21
  .then(generator => { generator.generateApi(); generator.generateModel(); });
320
22
  // require('./index.js')({swaggerDownloader});
@@ -0,0 +1,4 @@
1
+ export const MODEL_PRE = `import * as moment from 'moment';
2
+ `;
3
+ export const MODEL_POST = `
4
+ `;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@devlearning/swagger-generator",
3
- "version": "0.0.8",
3
+ "version": "0.0.10",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "type": "module",
7
7
  "scripts": {
8
8
  "dev": "ts-node --esm ./src/index.ts http://localhost:5208/swagger/v1/swagger.json autogeneration/output",
9
- "build": "ts-node --transpile-only ./src/index.ts"
9
+ "deploy": "npx tsc && npm publish"
10
10
  },
11
11
  "bin": {
12
12
  "swgen": "./dist/index.js"
@@ -0,0 +1,19 @@
1
+ export const API_PRE =
2
+ `import { HttpClient } from '@angular/common/http';
3
+ import { Observable, catchError, map } from 'rxjs';
4
+ import { httpOptions } from 'src/app/core/utils/http-options';
5
+ import * as Models from './model.autogenerated';
6
+
7
+ export abstract class ApiAutogeneratedService {
8
+ constructor(
9
+ private _http: HttpClient,
10
+ private _baseUrl: string,
11
+ ) { }
12
+
13
+ protected abstract _handleRequest<T>(request: T): T;
14
+ protected abstract _handleResponse<T>(response: T): T;
15
+ protected abstract _handleError(error: any, obs: any): any;
16
+ `;
17
+
18
+ export const API_POST =
19
+ `}`;