swagger-typescript-api 13.0.0-experimental-1 → 13.0.1

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 (81) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +26 -12
  3. package/cli/constants.js +3 -3
  4. package/cli/execute.js +52 -31
  5. package/cli/index.d.ts +1 -2
  6. package/cli/index.js +18 -17
  7. package/cli/operations/display-help.js +51 -29
  8. package/cli/parse-args.js +3 -3
  9. package/cli/process-option.js +28 -20
  10. package/index.d.ts +113 -8
  11. package/index.js +164 -135
  12. package/package.json +36 -30
  13. package/src/code-formatter.js +28 -13
  14. package/src/code-gen-process.js +367 -259
  15. package/src/commands/generate-templates/configuration.js +2 -2
  16. package/src/commands/generate-templates/index.js +1 -2
  17. package/src/commands/generate-templates/templates-gen-process.js +62 -35
  18. package/src/component-type-name-resolver.js +44 -0
  19. package/src/configuration.js +172 -96
  20. package/src/constants.js +28 -22
  21. package/src/index.js +3 -4
  22. package/src/schema-components-map.js +43 -25
  23. package/src/schema-parser/base-schema-parsers/array.js +43 -0
  24. package/src/schema-parser/base-schema-parsers/complex.js +51 -0
  25. package/src/schema-parser/base-schema-parsers/discriminator.js +304 -0
  26. package/src/schema-parser/base-schema-parsers/enum.js +158 -0
  27. package/src/schema-parser/base-schema-parsers/object.js +105 -0
  28. package/src/schema-parser/base-schema-parsers/primitive.js +63 -0
  29. package/src/schema-parser/complex-schema-parsers/all-of.js +26 -0
  30. package/src/schema-parser/complex-schema-parsers/any-of.js +27 -0
  31. package/src/schema-parser/complex-schema-parsers/not.js +9 -0
  32. package/src/schema-parser/complex-schema-parsers/one-of.js +27 -0
  33. package/src/schema-parser/mono-schema-parser.js +48 -0
  34. package/src/schema-parser/schema-formatters.js +69 -60
  35. package/src/schema-parser/schema-parser-fabric.js +131 -0
  36. package/src/schema-parser/schema-parser.js +234 -425
  37. package/src/schema-parser/schema-utils.js +165 -67
  38. package/src/schema-parser/util/enum-key-resolver.js +26 -0
  39. package/src/schema-routes/schema-routes.js +1222 -0
  40. package/src/schema-routes/util/specific-arg-name-resolver.js +26 -0
  41. package/src/schema-walker.js +93 -0
  42. package/src/swagger-schema-resolver.js +61 -28
  43. package/src/templates-worker.js +240 -0
  44. package/src/translators/javascript.js +83 -0
  45. package/src/translators/translator.js +35 -0
  46. package/src/type-name-formatter.js +43 -22
  47. package/src/util/file-system.js +30 -14
  48. package/src/util/id.js +2 -2
  49. package/src/util/internal-case.js +1 -1
  50. package/src/util/logger.js +46 -20
  51. package/src/util/name-resolver.js +52 -60
  52. package/src/util/object-assign.js +7 -3
  53. package/src/util/pascal-case.js +1 -1
  54. package/src/util/request.js +5 -5
  55. package/src/util/sort-by-property.js +17 -0
  56. package/templates/README.md +17 -17
  57. package/templates/base/README.md +7 -7
  58. package/templates/base/data-contract-jsdoc.ejs +37 -37
  59. package/templates/base/data-contracts.ejs +40 -27
  60. package/templates/base/enum-data-contract.ejs +12 -12
  61. package/templates/base/http-client.ejs +3 -3
  62. package/templates/base/http-clients/axios-http-client.ejs +139 -138
  63. package/templates/base/http-clients/fetch-http-client.ejs +224 -224
  64. package/templates/base/interface-data-contract.ejs +10 -10
  65. package/templates/base/object-field-jsdoc.ejs +28 -28
  66. package/templates/base/route-docs.ejs +30 -30
  67. package/templates/base/route-name.ejs +42 -42
  68. package/templates/base/route-type.ejs +22 -21
  69. package/templates/base/type-data-contract.ejs +15 -15
  70. package/templates/default/README.md +6 -6
  71. package/templates/default/api.ejs +69 -68
  72. package/templates/default/procedure-call.ejs +100 -100
  73. package/templates/default/route-types.ejs +32 -32
  74. package/templates/modular/README.md +6 -6
  75. package/templates/modular/api.ejs +28 -28
  76. package/templates/modular/procedure-call.ejs +100 -100
  77. package/templates/modular/route-types.ejs +18 -18
  78. package/src/schema-parser/schema-processor.js +0 -79
  79. package/src/schema-parser/schema-routes.js +0 -950
  80. package/src/templates.js +0 -182
  81. package/src/translators/JavaScript.js +0 -60
@@ -1,32 +1,34 @@
1
- const { objectAssign } = require("./util/object-assign");
2
- const _ = require("lodash");
3
- const CONSTANTS = require("./constants");
4
- const { ComponentTypeNameResolver } = require("./util/name-resolver");
5
- const { cosmiconfigSync } = require("cosmiconfig");
1
+ /* eslint-disable no-unused-vars */
2
+ const { objectAssign } = require('./util/object-assign');
3
+ const _ = require('lodash');
4
+ const CONSTANTS = require('./constants');
5
+ const { ComponentTypeNameResolver } = require('./component-type-name-resolver');
6
+ const { cosmiconfigSync } = require('cosmiconfig');
7
+ const ts = require('typescript');
6
8
 
7
9
  const TsKeyword = {
8
- Number: "number",
9
- String: "string",
10
- Boolean: "boolean",
11
- Any: "any",
12
- Void: "void",
13
- Unknown: "unknown",
14
- Null: "null",
15
- Undefined: "undefined",
16
- Object: "object",
17
- File: "File",
18
- Date: "Date",
19
- Type: "type",
20
- Enum: "enum",
21
- Interface: "interface",
22
- Array: "Array",
23
- Record: "Record",
24
- Intersection: "&",
25
- Union: "|",
10
+ Number: 'number',
11
+ String: 'string',
12
+ Boolean: 'boolean',
13
+ Any: 'any',
14
+ Void: 'void',
15
+ Unknown: 'unknown',
16
+ Null: 'null',
17
+ Undefined: 'undefined',
18
+ Object: 'object',
19
+ File: 'File',
20
+ Date: 'Date',
21
+ Type: 'type',
22
+ Enum: 'enum',
23
+ Interface: 'interface',
24
+ Array: 'Array',
25
+ Record: 'Record',
26
+ Intersection: '&',
27
+ Union: '|',
26
28
  };
27
29
 
28
30
  const TsCodeGenKeyword = {
29
- UtilRequiredKeys: "UtilRequiredKeys",
31
+ UtilRequiredKeys: 'UtilRequiredKeys',
30
32
  };
31
33
 
32
34
  /**
@@ -35,7 +37,7 @@ const TsCodeGenKeyword = {
35
37
  class CodeGenConfig {
36
38
  version = CONSTANTS.PROJECT_VERSION;
37
39
  /** CLI flag */
38
- templates = "../templates/default";
40
+ templates = '';
39
41
  /** CLI flag */
40
42
  generateResponses = false;
41
43
  /** CLI flag */
@@ -72,12 +74,13 @@ class CodeGenConfig {
72
74
  extractRequestBody = false;
73
75
  extractResponseBody = false;
74
76
  extractResponseError = false;
77
+ extractResponses = false;
75
78
  extractEnums = false;
76
79
  fileNames = {
77
- dataContracts: "data-contracts",
78
- routeTypes: "route-types",
79
- httpClient: "http-client",
80
- outOfModuleApi: "Common",
80
+ dataContracts: 'data-contracts',
81
+ routeTypes: 'route-types',
82
+ httpClient: 'http-client',
83
+ outOfModuleApi: 'Common',
81
84
  };
82
85
  routeNameDuplicatesMap = new Map();
83
86
  prettierOptions = { ...CONSTANTS.PRETTIER_OPTIONS };
@@ -89,7 +92,7 @@ class CodeGenConfig {
89
92
  onPreParseSchema: (originalSchema, typeName, schemaType) => void 0,
90
93
  onParseSchema: (originalSchema, parsedSchema) => parsedSchema,
91
94
  onCreateRoute: (routeData) => routeData,
92
- onInit: (config) => config,
95
+ onInit: (config, codeGenProcess) => config,
93
96
  onPrepareConfig: (apiConfig) => apiConfig,
94
97
  onCreateRequestParams: (rawType) => {},
95
98
  onCreateRouteName: () => {},
@@ -102,71 +105,113 @@ class CodeGenConfig {
102
105
  unwrapResponseData = false;
103
106
  disableThrowOnError = false;
104
107
  sortTypes = false;
108
+ sortRoutes = false;
105
109
  templatePaths = {
106
110
  /** `templates/base` */
107
- base: "",
111
+ base: '',
108
112
  /** `templates/default` */
109
- default: "",
113
+ default: '',
110
114
  /** `templates/modular` */
111
- modular: "",
115
+ modular: '',
112
116
  /** usage path if `--templates` option is not set */
113
- original: "",
117
+ original: '',
114
118
  /** custom path to templates (`--templates`) */
115
- custom: "",
119
+ custom: '',
116
120
  };
117
121
  /** Record<templateName, templateContent> */
118
122
  templatesToRender = {
119
- api: "",
120
- dataContracts: "",
121
- dataContractJsDoc: "",
122
- interfaceDataContract: "",
123
- typeDataContract: "",
124
- enumDataContract: "",
125
- objectFieldJsDoc: "",
126
- httpClient: "",
127
- routeTypes: "",
128
- routeName: "",
123
+ api: '',
124
+ dataContracts: '',
125
+ dataContractJsDoc: '',
126
+ interfaceDataContract: '',
127
+ typeDataContract: '',
128
+ enumDataContract: '',
129
+ objectFieldJsDoc: '',
130
+ httpClient: '',
131
+ routeTypes: '',
132
+ routeName: '',
129
133
  };
134
+ /**
135
+ * @type {Record<string, (...args: any[]) => MonoSchemaParser>}
136
+ */
137
+ schemaParsers = {};
130
138
  toJS = false;
131
139
  silent = false;
132
- typePrefix = "";
133
- typeSuffix = "";
134
- enumKeyPrefix = "";
135
- enumKeySuffix = "";
140
+ typePrefix = '';
141
+ typeSuffix = '';
142
+ enumKeyPrefix = '';
143
+ enumKeySuffix = '';
136
144
  patch = false;
137
- componentTypeNameResolver = new ComponentTypeNameResolver(null, []);
145
+ /** @type {ComponentTypeNameResolver} */
146
+ componentTypeNameResolver;
138
147
  /** name of the main exported class */
139
- apiClassName = "Api";
148
+ apiClassName = 'Api';
140
149
  debug = false;
141
150
  anotherArrayType = false;
142
151
  internalTemplateOptions = {
143
152
  addUtilRequiredKeysType: false,
144
153
  };
145
154
  extraTemplates = [];
146
- input = "";
155
+ input = '';
147
156
  modular = false;
148
- output = "";
149
- url = "";
157
+ output = '';
158
+ url = '';
150
159
  cleanOutput = false;
151
160
  spec = null;
152
- fileName = "Api.ts";
161
+ fileName = 'Api.ts';
153
162
  authorizationToken = void 0;
154
163
  requestOptions = null;
155
164
 
156
165
  jsPrimitiveTypes = [];
157
166
  jsEmptyTypes = [];
158
- fixInvalidTypeNamePrefix = "Type";
159
- fixInvalidEnumKeyPrefix = "Value";
167
+ fixInvalidTypeNamePrefix = 'Type';
168
+ fixInvalidEnumKeyPrefix = 'Value';
169
+
170
+ enumKeyResolverName = 'Value';
171
+ typeNameResolverName = 'ComponentType';
172
+ specificArgNameResolverName = 'arg';
160
173
 
161
174
  successResponseStatusRange = [200, 299];
162
175
 
163
176
  /** @type {ExtractingOptions} */
164
177
  extractingOptions = {
165
- requestBodySuffix: ["Payload", "Body", "Input"],
166
- requestParamsSuffix: ["Params"],
167
- responseBodySuffix: ["Data", "Result", "Output"],
168
- responseErrorSuffix: ["Error", "Fail", "Fails", "ErrorData", "HttpError", "BadResponse"],
178
+ requestBodySuffix: ['Payload', 'Body', 'Input'],
179
+ requestParamsSuffix: ['Params'],
180
+ responseBodySuffix: ['Data', 'Result', 'Output'],
181
+ responseErrorSuffix: [
182
+ 'Error',
183
+ 'Fail',
184
+ 'Fails',
185
+ 'ErrorData',
186
+ 'HttpError',
187
+ 'BadResponse',
188
+ ],
189
+ enumSuffix: ['Enum'],
190
+ discriminatorMappingSuffix: ['Mapping', 'Mapper', 'MapType'],
191
+ discriminatorAbstractPrefix: [
192
+ 'Base',
193
+ 'Abstract',
194
+ 'Discriminator',
195
+ 'Internal',
196
+ 'Polymorph',
197
+ ],
198
+ };
199
+
200
+ compilerTsConfig = {
201
+ module: 'ESNext',
202
+ noImplicitReturns: true,
203
+ alwaysStrict: true,
204
+ target: ts.ScriptTarget.ESNext,
205
+ declaration: true,
206
+ noImplicitAny: false,
207
+ sourceMap: false,
208
+ removeComments: false,
209
+ disableSizeLimit: true,
210
+ esModuleInterop: true,
211
+ emitDecoratorMetadata: true,
212
+ skipLibCheck: true,
169
213
  };
214
+ customTranslator;
170
215
 
171
216
  Ts = {
172
217
  Keyword: _.cloneDeep(TsKeyword),
@@ -196,32 +241,46 @@ class CodeGenConfig {
196
241
  /**
197
242
  * $A
198
243
  */
199
- NullValue: (content) => content,
244
+ NullValue: (content) => `null`,
200
245
  /**
201
246
  * $A1 | $A2
202
247
  */
203
- UnionType: (contents) => _.join(_.uniq(contents), ` ${this.Ts.Keyword.Union} `),
248
+ UnionType: (contents) =>
249
+ _.join(_.uniq(contents), ` ${this.Ts.Keyword.Union} `),
204
250
  /**
205
251
  * ($A1)
206
252
  */
207
- ExpressionGroup: (content) => (content ? `(${content})` : ""),
253
+ ExpressionGroup: (content) => (content ? `(${content})` : ''),
208
254
  /**
209
255
  * $A1 & $A2
210
256
  */
211
- IntersectionType: (contents) => _.join(_.uniq(contents), ` ${this.Ts.Keyword.Intersection} `),
257
+ IntersectionType: (contents) =>
258
+ _.join(_.uniq(contents), ` ${this.Ts.Keyword.Intersection} `),
212
259
  /**
213
260
  * Record<$A1, $A2>
214
261
  */
215
- RecordType: (key, value) => this.Ts.TypeWithGeneric(this.Ts.Keyword.Record, [key, value]),
262
+ RecordType: (key, value) =>
263
+ this.Ts.TypeWithGeneric(this.Ts.Keyword.Record, [key, value]),
216
264
  /**
217
265
  * readonly $key?:$value
218
266
  */
219
267
  TypeField: ({ readonly, key, optional, value }) =>
220
- _.compact([readonly && "readonly ", key, optional && "?", ": ", value]).join(""),
268
+ _.compact([
269
+ readonly && 'readonly ',
270
+ key,
271
+ optional && '?',
272
+ ': ',
273
+ value,
274
+ ]).join(''),
221
275
  /**
222
276
  * [key: $A1]: $A2
223
277
  */
224
278
  InterfaceDynamicField: (key, value) => `[key: ${key}]: ${value}`,
279
+
280
+ /**
281
+ * EnumName.EnumKey
282
+ */
283
+ EnumUsageKey: (enumStruct, key) => `${enumStruct}.${key}`,
225
284
  /**
226
285
  * $A1 = $A2
227
286
  */
@@ -232,7 +291,10 @@ class CodeGenConfig {
232
291
  * $AN.key = $AN.value,
233
292
  */
234
293
  EnumFieldsWrapper: (contents) =>
235
- _.map(contents, ({ key, value }) => ` ${this.Ts.EnumField(key, value)}`).join(",\n"),
294
+ _.map(
295
+ contents,
296
+ ({ key, value }) => ` ${this.Ts.EnumField(key, value)}`,
297
+ ).join(',\n'),
236
298
  /**
237
299
  * {\n $A \n}
238
300
  */
@@ -244,26 +306,28 @@ class CodeGenConfig {
244
306
  [
245
307
  ...(contents.length === 1
246
308
  ? [`/** ${contents[0]} */`]
247
- : ["/**", ...contents.map((content) => ` * ${content}`), " */"]),
309
+ : ['/**', ...contents.map((content) => ` * ${content}`), ' */']),
248
310
  ].map((part) => `${formatFn ? formatFn(part) : part}\n`),
249
311
  /**
250
312
  * $A1<...$A2.join(,)>
251
313
  */
252
314
  TypeWithGeneric: (typeName, genericArgs) => {
253
- return `${typeName}${genericArgs.length ? `<${genericArgs.join(",")}>` : ""}`;
315
+ return `${typeName}${
316
+ genericArgs.length ? `<${genericArgs.join(',')}>` : ''
317
+ }`;
254
318
  },
255
319
  /**
256
320
  * [$A1, $A2, ...$AN]
257
321
  */
258
322
  Tuple: (values) => {
259
- return `[${values.join(", ")}]`;
323
+ return `[${values.join(', ')}]`;
260
324
  },
261
325
  };
262
326
 
263
327
  /**
264
328
  * swagger schema type -> typescript type
265
329
  * https://json-schema.org/understanding-json-schema/reference/string.html#dates-and-times
266
- * @type {Record<string, string | ((schema: any, parser: SchemaProcessor) => string) | ({ $default: string } & Record<string, string | ((schema: any, parser: SchemaParser) => string)>)>}
330
+ * @type {Record<string, string | ((schema: any, parser: SchemaParser) => string) | ({ $default: string } & Record<string, string | ((schema: any, parser: SchemaParser) => string)>)>}
267
331
  */
268
332
  primitiveTypes = {
269
333
  integer: () => this.Ts.Keyword.Number,
@@ -277,39 +341,39 @@ class CodeGenConfig {
277
341
  /** formats */
278
342
  binary: () => this.Ts.Keyword.File,
279
343
  file: () => this.Ts.Keyword.File,
280
- "date-time": () => this.Ts.Keyword.String,
344
+ 'date-time': () => this.Ts.Keyword.String,
281
345
  time: () => this.Ts.Keyword.String,
282
346
  date: () => this.Ts.Keyword.String,
283
347
  duration: () => this.Ts.Keyword.String,
284
348
  email: () => this.Ts.Keyword.String,
285
- "idn-email": () => this.Ts.Keyword.String,
286
- "idn-hostname": () => this.Ts.Keyword.String,
349
+ 'idn-email': () => this.Ts.Keyword.String,
350
+ 'idn-hostname': () => this.Ts.Keyword.String,
287
351
  ipv4: () => this.Ts.Keyword.String,
288
352
  ipv6: () => this.Ts.Keyword.String,
289
353
  uuid: () => this.Ts.Keyword.String,
290
354
  uri: () => this.Ts.Keyword.String,
291
- "uri-reference": () => this.Ts.Keyword.String,
292
- "uri-template": () => this.Ts.Keyword.String,
293
- "json-pointer": () => this.Ts.Keyword.String,
294
- "relative-json-pointer": () => this.Ts.Keyword.String,
355
+ 'uri-reference': () => this.Ts.Keyword.String,
356
+ 'uri-template': () => this.Ts.Keyword.String,
357
+ 'json-pointer': () => this.Ts.Keyword.String,
358
+ 'relative-json-pointer': () => this.Ts.Keyword.String,
295
359
  regex: () => this.Ts.Keyword.String,
296
360
  },
297
361
  };
298
362
 
299
363
  templateInfos = [
300
- { name: "api", fileName: "api" },
301
- { name: "dataContracts", fileName: "data-contracts" },
302
- { name: "dataContractJsDoc", fileName: "data-contract-jsdoc" },
303
- { name: "interfaceDataContract", fileName: "interface-data-contract" },
304
- { name: "typeDataContract", fileName: "type-data-contract" },
305
- { name: "enumDataContract", fileName: "enum-data-contract" },
306
- { name: "objectFieldJsDoc", fileName: "object-field-jsdoc" },
307
- { name: "httpClient", fileName: "http-client" },
308
- { name: "routeTypes", fileName: "route-types" },
309
- { name: "routeName", fileName: "route-name" },
364
+ { name: 'api', fileName: 'api' },
365
+ { name: 'dataContracts', fileName: 'data-contracts' },
366
+ { name: 'dataContractJsDoc', fileName: 'data-contract-jsdoc' },
367
+ { name: 'interfaceDataContract', fileName: 'interface-data-contract' },
368
+ { name: 'typeDataContract', fileName: 'type-data-contract' },
369
+ { name: 'enumDataContract', fileName: 'enum-data-contract' },
370
+ { name: 'objectFieldJsDoc', fileName: 'object-field-jsdoc' },
371
+ { name: 'httpClient', fileName: 'http-client' },
372
+ { name: 'routeTypes', fileName: 'route-types' },
373
+ { name: 'routeName', fileName: 'route-name' },
310
374
  ];
311
375
 
312
- templateExtensions = [".eta", ".ejs"];
376
+ templateExtensions = ['.eta', '.ejs'];
313
377
 
314
378
  /**
315
379
  * @param config {Partial<GenerateApiConfiguration['config']>}
@@ -321,7 +385,7 @@ class CodeGenConfig {
321
385
  constants,
322
386
  templateInfos,
323
387
  hooks,
324
- ...params
388
+ ...otherConfig
325
389
  }) {
326
390
  objectAssign(this.Ts, codeGenConstructs);
327
391
  objectAssign(this.primitiveTypes, primitiveTypeConstructs);
@@ -329,8 +393,11 @@ class CodeGenConfig {
329
393
  this.defaultResponseType = this.Ts.Keyword.Void;
330
394
 
331
395
  this.update({
332
- ...params,
333
- prettierOptions: prettierOptions === undefined ? getDefaultPrettierOptions() : prettierOptions,
396
+ ...otherConfig,
397
+ prettierOptions:
398
+ prettierOptions === undefined
399
+ ? getDefaultPrettierOptions()
400
+ : prettierOptions,
334
401
  hooks: _.merge(this.hooks, hooks || {}),
335
402
  constants: {
336
403
  ...CONSTANTS,
@@ -339,8 +406,17 @@ class CodeGenConfig {
339
406
  templateInfos: templateInfos || this.templateInfos,
340
407
  });
341
408
 
342
- this.jsPrimitiveTypes = [this.Ts.Keyword.Number, this.Ts.Keyword.String, this.Ts.Keyword.Boolean];
409
+ this.jsPrimitiveTypes = [
410
+ this.Ts.Keyword.Number,
411
+ this.Ts.Keyword.String,
412
+ this.Ts.Keyword.Boolean,
413
+ ];
343
414
  this.jsEmptyTypes = [this.Ts.Keyword.Null, this.Ts.Keyword.Undefined];
415
+ this.componentTypeNameResolver = new ComponentTypeNameResolver(
416
+ this,
417
+ null,
418
+ [],
419
+ );
344
420
  }
345
421
 
346
422
  /**
@@ -353,12 +429,12 @@ class CodeGenConfig {
353
429
  }
354
430
 
355
431
  const getDefaultPrettierOptions = () => {
356
- const prettier = cosmiconfigSync("prettier").search();
432
+ const prettier = cosmiconfigSync('prettier').search();
357
433
 
358
434
  if (prettier) {
359
435
  return {
360
436
  ...prettier.config,
361
- parser: "typescript",
437
+ parser: 'typescript',
362
438
  };
363
439
  }
364
440
 
package/src/constants.js CHANGED
@@ -1,27 +1,33 @@
1
- const packageJson = require("../package.json");
2
- const RESERVED_QUERY_ARG_NAMES = ["query", "queryParams", "queryArg"];
3
- const RESERVED_BODY_ARG_NAMES = ["data", "body", "reqBody"];
4
- const RESERVED_REQ_PARAMS_ARG_NAMES = ["params", "requestParams", "reqParams", "httpParams"];
5
- const RESERVED_PATH_ARG_NAMES = ["path", "pathParams"];
6
- const RESERVED_HEADER_ARG_NAMES = ["headers", "headersParams"];
1
+ const packageJson = require('../package.json');
2
+ const RESERVED_QUERY_ARG_NAMES = ['query', 'queryParams', 'queryArg'];
3
+ const RESERVED_BODY_ARG_NAMES = ['data', 'body', 'reqBody'];
4
+ const RESERVED_REQ_PARAMS_ARG_NAMES = [
5
+ 'params',
6
+ 'requestParams',
7
+ 'reqParams',
8
+ 'httpParams',
9
+ ];
10
+ const RESERVED_PATH_ARG_NAMES = ['path', 'pathParams'];
11
+ const RESERVED_HEADER_ARG_NAMES = ['headers', 'headersParams'];
7
12
 
8
13
  const SCHEMA_TYPES = {
9
- ARRAY: "array",
10
- OBJECT: "object",
11
- ENUM: "enum",
12
- REF: "$ref",
13
- PRIMITIVE: "primitive",
14
- COMPLEX: "complex",
15
- COMPLEX_ONE_OF: "oneOf",
16
- COMPLEX_ANY_OF: "anyOf",
17
- COMPLEX_ALL_OF: "allOf",
18
- COMPLEX_NOT: "not",
19
- COMPLEX_UNKNOWN: "__unknown",
14
+ ARRAY: 'array',
15
+ OBJECT: 'object',
16
+ ENUM: 'enum',
17
+ REF: '$ref',
18
+ PRIMITIVE: 'primitive',
19
+ COMPLEX: 'complex',
20
+ DISCRIMINATOR: 'discriminator',
21
+ COMPLEX_ONE_OF: 'oneOf',
22
+ COMPLEX_ANY_OF: 'anyOf',
23
+ COMPLEX_ALL_OF: 'allOf',
24
+ COMPLEX_NOT: 'not',
25
+ COMPLEX_UNKNOWN: '__unknown',
20
26
  };
21
27
 
22
28
  const HTTP_CLIENT = {
23
- FETCH: "fetch",
24
- AXIOS: "axios",
29
+ FETCH: 'fetch',
30
+ AXIOS: 'axios',
25
31
  };
26
32
 
27
33
  const PROJECT_VERSION = packageJson.version;
@@ -41,7 +47,7 @@ const FILE_PREFIX = `/* eslint-disable */
41
47
 
42
48
  module.exports = {
43
49
  FILE_PREFIX,
44
- DEFAULT_BODY_ARG_NAME: "data",
50
+ DEFAULT_BODY_ARG_NAME: 'data',
45
51
  PROJECT_VERSION,
46
52
  SCHEMA_TYPES,
47
53
  HTTP_CLIENT,
@@ -53,7 +59,7 @@ module.exports = {
53
59
  PRETTIER_OPTIONS: {
54
60
  printWidth: 120,
55
61
  tabWidth: 2,
56
- trailingComma: "all",
57
- parser: "typescript",
62
+ trailingComma: 'all',
63
+ parser: 'typescript',
58
64
  },
59
65
  };
package/src/index.js CHANGED
@@ -6,10 +6,9 @@
6
6
  // License text available at https://opensource.org/licenses/MIT
7
7
  // Repository https://github.com/acacode/swagger-typescript-api
8
8
 
9
- const _ = require("lodash");
10
- const constants = require("./constants");
11
- const { CodeGenProcess } = require("./code-gen-process.js");
12
- const { generateTemplates } = require("./commands/generate-templates");
9
+ const constants = require('./constants');
10
+ const { CodeGenProcess } = require('./code-gen-process.js');
11
+ const { generateTemplates } = require('./commands/generate-templates');
13
12
 
14
13
  module.exports = {
15
14
  constants: constants,
@@ -1,31 +1,31 @@
1
- const _ = require("lodash");
1
+ const _ = require('lodash');
2
2
 
3
3
  class SchemaComponentsMap {
4
- /**
5
- * @type {Record<string, SchemaComponent>}
6
- */
7
- data = {};
8
- /**
9
- * @type {CodeGenConfig}
10
- */
4
+ /** @type {SchemaComponent[]} */
5
+ _data = [];
6
+ /** @type {CodeGenConfig} */
11
7
  config;
12
8
 
13
- constructor(config, schema) {
9
+ constructor({ config }) {
14
10
  this.config = config;
15
- this.processSchema(schema);
16
11
  }
17
12
 
18
- processSchema(schema) {
19
- this.data = {};
20
- if (!schema) return;
21
- _.each(schema.components, (component, componentName) =>
22
- _.each(component, (rawTypeData, typeName) => this.createComponent(componentName, typeName, rawTypeData)),
23
- );
13
+ clear() {
14
+ this._data = [];
24
15
  }
25
16
 
26
- createComponent(componentName, typeName, rawTypeData) {
27
- const $ref = `#/components/${componentName}/${typeName}`;
17
+ createRef = (paths) => {
18
+ return ['#', ...paths].join('/');
19
+ };
20
+
21
+ parseRef = (ref) => {
22
+ return ref.split('/');
23
+ };
28
24
 
25
+ createComponent($ref, rawTypeData) {
26
+ const parsed = this.parseRef($ref);
27
+ const typeName = parsed[parsed.length - 1];
28
+ const componentName = parsed[parsed.length - 2];
29
29
  const componentSchema = {
30
30
  $ref,
31
31
  typeName,
@@ -35,23 +35,41 @@ class SchemaComponentsMap {
35
35
  typeData: null,
36
36
  };
37
37
 
38
- const usageComponent = this.config.hooks.onCreateComponent(componentSchema) || componentSchema;
38
+ const usageComponent =
39
+ this.config.hooks.onCreateComponent(componentSchema) || componentSchema;
40
+
41
+ const refIndex = this._data.findIndex((c) => c.$ref === $ref);
39
42
 
40
- this.data[$ref] = usageComponent;
43
+ if (refIndex === -1) {
44
+ this._data.push(usageComponent);
45
+ } else {
46
+ this._data[refIndex] = usageComponent;
47
+ }
41
48
 
42
49
  return usageComponent;
43
50
  }
44
51
 
45
52
  /**
46
- * @param componentName {string}
47
53
  * @returns {SchemaComponent[]}
48
54
  */
49
- filter(componentName) {
50
- return _.filter(this.data, (v, ref) => _.startsWith(ref, `#/components/${componentName}`));
55
+ getComponents() {
56
+ return this._data;
57
+ }
58
+
59
+ /**
60
+ * @params {...string[]} componentNames
61
+ * @returns {SchemaComponent[]}
62
+ */
63
+ filter(...componentNames) {
64
+ return _.filter(this._data, (it) =>
65
+ componentNames.some((componentName) =>
66
+ _.startsWith(it.$ref, `#/components/${componentName}`),
67
+ ),
68
+ );
51
69
  }
52
70
 
53
- get(ref) {
54
- return this.data[ref] || null;
71
+ get($ref) {
72
+ return this._data.find((c) => c.$ref === $ref) || null;
55
73
  }
56
74
  }
57
75