forked from acacode/swagger-typescript-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
413 lines (395 loc) · 12.7 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
#!/usr/bin/env node
// Copyright (c) 2019-present acacode
// Node module: swagger-typescript-api
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
// Repository https://github.com/acacode/swagger-typescript-api
const { version, name } = require('./package.json');
const { cli } = require('./cli');
const { generateApi, generateTemplates } = require('./src');
const { HTTP_CLIENT } = require('./src/constants');
const { resolve } = require('path');
const _ = require("lodash");
const { CodeGenConfig } = require('./src/configuration');
const {
TemplatesGenConfig,
} = require('./src/commands/generate-templates/configuration');
const codeGenBaseConfig = new CodeGenConfig({});
const templateGenBaseConfig = new TemplatesGenConfig({});
function onCreateComponent(component) {
function mapEntries(object, mapCallbackFn) {
return Object.fromEntries(Object.entries(object).map(mapCallbackFn));
}
function camelCaseProperties(object) {
if (Array.isArray(object)) {
return object.map(camelCaseProperties);
} else if (typeof object === 'object' && object !== null) {
if (object.properties) {
object.properties = camelCaseProperties(object.properties);
}
if (object.items) {
object.items = camelCaseProperties(object.items);
}
['allOf', 'anyOf', 'oneOf'].forEach((keyword) => {
if (object[keyword]) {
object[keyword] = camelCaseProperties(object[keyword]);
}
});
if (
object.additionalProperties &&
typeof object.additionalProperties === 'object'
) {
object.additionalProperties = camelCaseProperties(
object.additionalProperties
);
}
if (object.required && Array.isArray(object.required)) {
object.required = object.required.map(_.camelCase);
}
return mapEntries(object, ([key, value]) => {
return [
/**
* Transforming key into camel case format needs to be done like follow
* because camelCase method from lodash removes special characters while
* performing transformation into camel case format.
* e.g., $ref key, that is introduced in OpenAPI 3.0,
* will be converted into ref if camelCase method itself is used
* @see https://swagger.io/docs/specification/using-ref/
*/
key.replace(/\w+/g, _.camelCase),
camelCaseProperties(value),
]
});
} else {
return object;
}
}
component.rawTypeData = camelCaseProperties(component.rawTypeData);
return component;
}
const program = cli({
name: name,
alias: 'sta',
version: version,
description:
'Generate api via swagger scheme.\nSupports OA 3.0, 2.0, JSON, yaml.',
options: [
{
flags: '-p, --path <string>',
description: 'path/url to swagger scheme',
required: true,
},
{
flags: '-o, --output <string>',
description: 'output path of typescript api file',
default: './',
},
{
flags: '-n, --name <string>',
description: 'name of output typescript api file',
default: codeGenBaseConfig.fileName,
},
{
flags: '-t, --templates <string>',
description: 'path to folder containing templates',
},
{
flags: '-d, --default-as-success',
description:
'use "default" response status code as success response too.\n' +
'some swagger schemas use "default" response status code as success response type by default.',
default: codeGenBaseConfig.defaultResponseAsSuccess,
internal: { name: 'defaultResponseAsSuccess' },
},
{
flags: '-r, --responses',
description:
'generate additional information about request responses\n' +
'also add typings for bad responses',
default: codeGenBaseConfig.generateResponses,
internal: { name: 'generateResponses' },
},
{
flags: '--union-enums',
description: 'generate all "enum" types as union types (T1 | T2 | TN)',
default: codeGenBaseConfig.generateUnionEnums,
internal: { name: 'generateUnionEnums' },
},
{
flags: '--add-readonly',
description: 'generate readonly properties',
default: codeGenBaseConfig.addReadonly,
},
{
flags: '--route-types',
description: 'generate type definitions for API routes',
default: codeGenBaseConfig.generateRouteTypes,
internal: { name: 'generateRouteTypes' },
},
{
flags: '--no-client',
description: 'do not generate an API class',
default: codeGenBaseConfig.generateClient,
},
{
flags: '--enum-names-as-values',
description:
"use values in 'x-enumNames' as enum values (not only as keys)",
default: codeGenBaseConfig.enumNamesAsValues,
},
{
flags: '--extract-request-params',
description:
'extract request params to data contract (Also combine path params and query params into one object)',
default: codeGenBaseConfig.extractRequestParams,
internal: { formatter: Boolean },
},
{
flags: '--extract-request-body',
description: 'extract request body type to data contract',
default: codeGenBaseConfig.extractRequestBody,
internal: { formatter: Boolean },
},
{
flags: '--extract-response-body',
description: 'extract response body type to data contract',
default: codeGenBaseConfig.extractResponseBody,
internal: { formatter: Boolean },
},
{
flags: '--extract-response-error',
description: 'extract response error type to data contract',
default: codeGenBaseConfig.extractResponseError,
internal: { formatter: Boolean },
},
{
flags: '--extract-responses',
description: 'extract all responses described in /components/responses',
default: codeGenBaseConfig.extractResponses,
internal: { formatter: Boolean },
},
{
flags: '--modular',
description:
'generate separated files for http client, data contracts, and routes',
default: codeGenBaseConfig.modular,
internal: { formatter: Boolean },
},
{
flags: '--js',
description: 'generate js api module with declaration file',
default: codeGenBaseConfig.toJS,
internal: { formatter: Boolean, name: 'toJS' },
},
{
flags: '--module-name-index <number>',
description:
'determines which path index should be used for routes separation (example: GET:/fruites/getFruit -> index:0 -> moduleName -> fruites)',
default: codeGenBaseConfig.moduleNameIndex,
internal: { formatter: (moduleNameIndex) => +moduleNameIndex || 0 },
},
{
flags: '--module-name-first-tag',
description: 'splits routes based on the first tag',
default: codeGenBaseConfig.moduleNameFirstTag,
},
{
flags: '--disableStrictSSL',
description: 'disabled strict SSL',
default: codeGenBaseConfig.disableStrictSSL,
internal: { formatter: Boolean },
},
{
flags: '--disableProxy',
description: 'disabled proxy',
default: codeGenBaseConfig.disableProxy,
internal: { formatter: Boolean },
},
{
flags: '--axios',
description: 'generate axios http client',
default: codeGenBaseConfig.httpClientType === HTTP_CLIENT.AXIOS,
},
{
flags: '--unwrap-response-data',
description: 'unwrap the data item from the response',
default: codeGenBaseConfig.unwrapResponseData,
},
{
flags: '--disable-throw-on-error',
description: 'Do not throw an error when response.ok is not true',
default: codeGenBaseConfig.disableThrowOnError,
},
{
flags: '--single-http-client',
description: 'Ability to send HttpClient instance to Api constructor',
default: codeGenBaseConfig.singleHttpClient,
internal: { formatter: Boolean },
},
{
flags: '--silent',
description: 'Output only errors to console',
default: codeGenBaseConfig.silent,
internal: { formatter: Boolean },
},
{
flags: '--default-response <type>',
description: 'default type for empty response schema',
default: codeGenBaseConfig.defaultResponseType,
internal: { name: 'defaultResponseType' },
},
{
flags: '--type-prefix <string>',
description: 'data contract name prefix',
default: codeGenBaseConfig.typePrefix,
},
{
flags: '--type-suffix <string>',
description: 'data contract name suffix',
default: codeGenBaseConfig.typeSuffix,
},
{
flags: '--clean-output',
description:
'clean output folder before generate api. WARNING: May cause data loss',
default: codeGenBaseConfig.cleanOutput,
internal: { formatter: Boolean },
},
{
flags: '--api-class-name <string>',
description: 'name of the api class',
default: codeGenBaseConfig.apiClassName,
},
{
flags: '--patch',
description: 'fix up small errors in the swagger source definition',
default: codeGenBaseConfig.patch,
internal: { formatter: Boolean },
},
{
flags: '--debug',
description: 'additional information about processes inside this tool',
default: codeGenBaseConfig.debug,
},
{
flags: '--another-array-type',
description: 'generate array types as Array<Type> (by default Type[])',
default: codeGenBaseConfig.anotherArrayType,
},
{
flags: '--sort-types',
description: 'sort fields and types',
default: codeGenBaseConfig.sortTypes,
},
{
flags: '--extract-enums',
description:
'extract all enums from inline interface\\type content to typescript enum construction',
default: codeGenBaseConfig.extractEnums,
},
{
flags: '--sort-routes',
description: 'sort routes in alphabetical order',
default: codeGenBaseConfig.sortRoutes,
},
{
flags: '--custom-config <string>',
description: 'custom config: primitiveTypeConstructs, hooks, ... ',
default: '',
},
],
});
program.addCommand({
name: 'generate-templates',
description: `Generate ".ejs" templates needed for generate api`,
options: [
{
flags: '-o, --output <string>',
description: 'output path of generated templates',
default: templateGenBaseConfig.output,
},
{
flags: '-m, --modular',
description:
'generate templates needed to separate files for http client, data contracts, and routes',
default: templateGenBaseConfig.modular,
internal: { formatter: Boolean },
},
{
flags: '--http-client <string>',
description: `http client type (possible values: ${Object.values(
HTTP_CLIENT,
)
.map((v) => `"${v}"`)
.join(', ')})`,
default: templateGenBaseConfig.httpClientType,
internal: { name: 'httpClientType' },
},
{
flags: '-c, --clean-output',
description:
'clean output folder before generate template. WARNING: May cause data loss',
default: templateGenBaseConfig.cleanOutput,
internal: { formatter: Boolean },
},
{
flags: '-r, --rewrite',
description: 'rewrite content in existing templates',
default: templateGenBaseConfig.rewrite,
internal: { formatter: Boolean },
},
{
flags: '--silent',
description: 'Output only errors to console',
default: templateGenBaseConfig.silent,
internal: { formatter: Boolean },
},
],
});
const main = async () => {
const { command, options } = await program.execute({ args: process.argv });
let customConfig = null;
if (options.customConfig) {
try {
const customConfigPath = resolve(process.cwd(), options.customConfig);
console.log(`✨ found custom config at: ${customConfigPath}`);
customConfig = require(customConfigPath);
} catch (e) {
/* empty */
}
}
try {
switch (command) {
case null: {
await generateApi({
...options,
name: options.name,
url: options.path,
generateRouteTypes: options.routeTypes,
generateClient: !!(options.axios || options.client),
httpClientType: options.axios ? HTTP_CLIENT.AXIOS : HTTP_CLIENT.FETCH,
input: resolve(process.cwd(), options.path),
output: resolve(process.cwd(), options.output || '.'),
hooks: {
onCreateComponent
},
...customConfig,
});
break;
}
case 'generate-templates': {
await generateTemplates(options);
break;
}
default: {
break;
}
}
} catch (e) {
console.error(e);
process.exit(1);
return;
}
process.exit(0);
};
main();