swagger-typescript-api

Форк
0
350 строк · 10.8 Кб
1
#!/usr/bin/env node
2

3
// Copyright (c) 2019-present acacode
4
// Node module: swagger-typescript-api
5
// This file is licensed under the MIT License.
6
// License text available at https://opensource.org/licenses/MIT
7
// Repository https://github.com/acacode/swagger-typescript-api
8

9
const { version, name } = require('./package.json');
10
const { cli } = require('./cli');
11
const { generateApi, generateTemplates } = require('./src');
12
const { HTTP_CLIENT } = require('./src/constants');
13
const { resolve } = require('path');
14
const { CodeGenConfig } = require('./src/configuration');
15
const {
16
  TemplatesGenConfig,
17
} = require('./src/commands/generate-templates/configuration');
18

19
const codeGenBaseConfig = new CodeGenConfig({});
20
const templateGenBaseConfig = new TemplatesGenConfig({});
21

22
const program = cli({
23
  name: name,
24
  alias: 'sta',
25
  version: version,
26
  description:
27
    'Generate api via swagger scheme.\nSupports OA 3.0, 2.0, JSON, yaml.',
28
  options: [
29
    {
30
      flags: '-p, --path <string>',
31
      description: 'path/url to swagger scheme',
32
      required: true,
33
    },
34
    {
35
      flags: '-o, --output <string>',
36
      description: 'output path of typescript api file',
37
      default: './',
38
    },
39
    {
40
      flags: '-n, --name <string>',
41
      description: 'name of output typescript api file',
42
      default: codeGenBaseConfig.fileName,
43
    },
44
    {
45
      flags: '-t, --templates <string>',
46
      description: 'path to folder containing templates',
47
    },
48
    {
49
      flags: '-d, --default-as-success',
50
      description:
51
        'use "default" response status code as success response too.\n' +
52
        'some swagger schemas use "default" response status code as success response type by default.',
53
      default: codeGenBaseConfig.defaultResponseAsSuccess,
54
      internal: { name: 'defaultResponseAsSuccess' },
55
    },
56
    {
57
      flags: '-r, --responses',
58
      description:
59
        'generate additional information about request responses\n' +
60
        'also add typings for bad responses',
61
      default: codeGenBaseConfig.generateResponses,
62
      internal: { name: 'generateResponses' },
63
    },
64
    {
65
      flags: '--union-enums',
66
      description: 'generate all "enum" types as union types (T1 | T2 | TN)',
67
      default: codeGenBaseConfig.generateUnionEnums,
68
      internal: { name: 'generateUnionEnums' },
69
    },
70
    {
71
      flags: '--add-readonly',
72
      description: 'generate readonly properties',
73
      default: codeGenBaseConfig.addReadonly,
74
    },
75
    {
76
      flags: '--route-types',
77
      description: 'generate type definitions for API routes',
78
      default: codeGenBaseConfig.generateRouteTypes,
79
      internal: { name: 'generateRouteTypes' },
80
    },
81
    {
82
      flags: '--no-client',
83
      description: 'do not generate an API class',
84
      default: codeGenBaseConfig.generateClient,
85
    },
86
    {
87
      flags: '--enum-names-as-values',
88
      description:
89
        "use values in 'x-enumNames' as enum values (not only as keys)",
90
      default: codeGenBaseConfig.enumNamesAsValues,
91
    },
92
    {
93
      flags: '--extract-request-params',
94
      description:
95
        'extract request params to data contract (Also combine path params and query params into one object)',
96
      default: codeGenBaseConfig.extractRequestParams,
97
      internal: { formatter: Boolean },
98
    },
99
    {
100
      flags: '--extract-request-body',
101
      description: 'extract request body type to data contract',
102
      default: codeGenBaseConfig.extractRequestBody,
103
      internal: { formatter: Boolean },
104
    },
105
    {
106
      flags: '--extract-response-body',
107
      description: 'extract response body type to data contract',
108
      default: codeGenBaseConfig.extractResponseBody,
109
      internal: { formatter: Boolean },
110
    },
111
    {
112
      flags: '--extract-response-error',
113
      description: 'extract response error type to data contract',
114
      default: codeGenBaseConfig.extractResponseError,
115
      internal: { formatter: Boolean },
116
    },
117
    {
118
      flags: '--extract-responses',
119
      description: 'extract all responses described in /components/responses',
120
      default: codeGenBaseConfig.extractResponses,
121
      internal: { formatter: Boolean },
122
    },
123
    {
124
      flags: '--modular',
125
      description:
126
        'generate separated files for http client, data contracts, and routes',
127
      default: codeGenBaseConfig.modular,
128
      internal: { formatter: Boolean },
129
    },
130
    {
131
      flags: '--js',
132
      description: 'generate js api module with declaration file',
133
      default: codeGenBaseConfig.toJS,
134
      internal: { formatter: Boolean, name: 'toJS' },
135
    },
136
    {
137
      flags: '--module-name-index <number>',
138
      description:
139
        'determines which path index should be used for routes separation (example: GET:/fruites/getFruit -> index:0 -> moduleName -> fruites)',
140
      default: codeGenBaseConfig.moduleNameIndex,
141
      internal: { formatter: (moduleNameIndex) => +moduleNameIndex || 0 },
142
    },
143
    {
144
      flags: '--module-name-first-tag',
145
      description: 'splits routes based on the first tag',
146
      default: codeGenBaseConfig.moduleNameFirstTag,
147
    },
148
    {
149
      flags: '--disableStrictSSL',
150
      description: 'disabled strict SSL',
151
      default: codeGenBaseConfig.disableStrictSSL,
152
      internal: { formatter: Boolean },
153
    },
154
    {
155
      flags: '--disableProxy',
156
      description: 'disabled proxy',
157
      default: codeGenBaseConfig.disableProxy,
158
      internal: { formatter: Boolean },
159
    },
160
    {
161
      flags: '--axios',
162
      description: 'generate axios http client',
163
      default: codeGenBaseConfig.httpClientType === HTTP_CLIENT.AXIOS,
164
    },
165
    {
166
      flags: '--unwrap-response-data',
167
      description: 'unwrap the data item from the response',
168
      default: codeGenBaseConfig.unwrapResponseData,
169
    },
170
    {
171
      flags: '--disable-throw-on-error',
172
      description: 'Do not throw an error when response.ok is not true',
173
      default: codeGenBaseConfig.disableThrowOnError,
174
    },
175
    {
176
      flags: '--single-http-client',
177
      description: 'Ability to send HttpClient instance to Api constructor',
178
      default: codeGenBaseConfig.singleHttpClient,
179
      internal: { formatter: Boolean },
180
    },
181
    {
182
      flags: '--silent',
183
      description: 'Output only errors to console',
184
      default: codeGenBaseConfig.silent,
185
      internal: { formatter: Boolean },
186
    },
187
    {
188
      flags: '--default-response <type>',
189
      description: 'default type for empty response schema',
190
      default: codeGenBaseConfig.defaultResponseType,
191
      internal: { name: 'defaultResponseType' },
192
    },
193
    {
194
      flags: '--type-prefix <string>',
195
      description: 'data contract name prefix',
196
      default: codeGenBaseConfig.typePrefix,
197
    },
198
    {
199
      flags: '--type-suffix <string>',
200
      description: 'data contract name suffix',
201
      default: codeGenBaseConfig.typeSuffix,
202
    },
203
    {
204
      flags: '--clean-output',
205
      description:
206
        'clean output folder before generate api. WARNING: May cause data loss',
207
      default: codeGenBaseConfig.cleanOutput,
208
      internal: { formatter: Boolean },
209
    },
210
    {
211
      flags: '--api-class-name <string>',
212
      description: 'name of the api class',
213
      default: codeGenBaseConfig.apiClassName,
214
    },
215
    {
216
      flags: '--patch',
217
      description: 'fix up small errors in the swagger source definition',
218
      default: codeGenBaseConfig.patch,
219
      internal: { formatter: Boolean },
220
    },
221
    {
222
      flags: '--debug',
223
      description: 'additional information about processes inside this tool',
224
      default: codeGenBaseConfig.debug,
225
    },
226
    {
227
      flags: '--another-array-type',
228
      description: 'generate array types as Array<Type> (by default Type[])',
229
      default: codeGenBaseConfig.anotherArrayType,
230
    },
231
    {
232
      flags: '--sort-types',
233
      description: 'sort fields and types',
234
      default: codeGenBaseConfig.sortTypes,
235
    },
236
    {
237
      flags: '--extract-enums',
238
      description:
239
        'extract all enums from inline interface\\type content to typescript enum construction',
240
      default: codeGenBaseConfig.extractEnums,
241
    },
242
    {
243
      flags: '--sort-routes',
244
      description: 'sort routes in alphabetical order',
245
      default: codeGenBaseConfig.sortRoutes,
246
    },
247
    {
248
      flags: '--custom-config <string>',
249
      description: 'custom config: primitiveTypeConstructs, hooks, ... ',
250
      default: '',
251
    },
252
  ],
253
});
254

255
program.addCommand({
256
  name: 'generate-templates',
257
  description: `Generate ".ejs" templates needed for generate api`,
258
  options: [
259
    {
260
      flags: '-o, --output <string>',
261
      description: 'output path of generated templates',
262
      default: templateGenBaseConfig.output,
263
    },
264
    {
265
      flags: '-m, --modular',
266
      description:
267
        'generate templates needed to separate files for http client, data contracts, and routes',
268
      default: templateGenBaseConfig.modular,
269
      internal: { formatter: Boolean },
270
    },
271
    {
272
      flags: '--http-client <string>',
273
      description: `http client type (possible values: ${Object.values(
274
        HTTP_CLIENT,
275
      )
276
        .map((v) => `"${v}"`)
277
        .join(', ')})`,
278
      default: templateGenBaseConfig.httpClientType,
279
      internal: { name: 'httpClientType' },
280
    },
281
    {
282
      flags: '-c, --clean-output',
283
      description:
284
        'clean output folder before generate template. WARNING: May cause data loss',
285
      default: templateGenBaseConfig.cleanOutput,
286
      internal: { formatter: Boolean },
287
    },
288
    {
289
      flags: '-r, --rewrite',
290
      description: 'rewrite content in existing templates',
291
      default: templateGenBaseConfig.rewrite,
292
      internal: { formatter: Boolean },
293
    },
294
    {
295
      flags: '--silent',
296
      description: 'Output only errors to console',
297
      default: templateGenBaseConfig.silent,
298
      internal: { formatter: Boolean },
299
    },
300
  ],
301
});
302

303
const main = async () => {
304
  const { command, options } = await program.execute({ args: process.argv });
305

306
  let customConfig = null;
307

308
  if (options.customConfig) {
309
    try {
310
      const customConfigPath = resolve(process.cwd(), options.customConfig);
311
      console.log(`✨ found custom config at: ${customConfigPath}`);
312
      customConfig = require(customConfigPath);
313
    } catch (e) {
314
      /* empty */
315
    }
316
  }
317

318
  try {
319
    switch (command) {
320
      case null: {
321
        await generateApi({
322
          ...options,
323
          name: options.name,
324
          url: options.path,
325
          generateRouteTypes: options.routeTypes,
326
          generateClient: !!(options.axios || options.client),
327
          httpClientType: options.axios ? HTTP_CLIENT.AXIOS : HTTP_CLIENT.FETCH,
328
          input: resolve(process.cwd(), options.path),
329
          output: resolve(process.cwd(), options.output || '.'),
330
          ...customConfig,
331
        });
332
        break;
333
      }
334
      case 'generate-templates': {
335
        await generateTemplates(options);
336
        break;
337
      }
338
      default: {
339
        break;
340
      }
341
    }
342
  } catch (e) {
343
    console.error(e);
344
    process.exit(1);
345
    return;
346
  }
347
  process.exit(0);
348
};
349

350
main();
351

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.