Skip to content

Commit e3e0e6e

Browse files
authored
Merge pull request #451 from acacode/next
Release 12.0.0
2 parents a0174e9 + 0c1baf8 commit e3e0e6e

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

49 files changed

+4514
-387
lines changed

CHANGELOG.md

Lines changed: 52 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,55 @@
11
# next release
22

3+
## 12.0.0
4+
5+
new hooks:
6+
```ts
7+
/** calls before parse\process route path */
8+
onPreBuildRoutePath: (routePath: string) => string | void;
9+
/** calls after parse\process route path */
10+
onBuildRoutePath: (data: BuildRoutePath) => BuildRoutePath | void;
11+
/** calls before insert path param name into string path interpolation */
12+
onInsertPathParam: (paramName: string, index: number, arr: BuildRouteParam[], resultRoute: string) => string | void;
13+
/** calls before parse any kind of schema */
14+
onPreParseSchema: (originalSchema: any, typeName: string, schemaType: string) => any;
15+
```
16+
BREAKING_CHANGE: add ability to custom prefix for autofix invalid enum keys, invalid type names with nodejs options (`fixInvalidTypeNamePrefix: string`, `fixInvalidEnumKeyPrefix: string`)
17+
BREAKING_CHANGE: by default all component enum schemas (even numeric) extracting as `enum` TS constructions (#344)
18+
feature: ability to extract all enums from nested types\interfaces to `enum` TS construction using `--extract-enums` option (#344)
19+
feature: ability to modify route path params before insert them into string (request url, #446, with using hook `onInsertPathParam`)
20+
feature: (nodejs) ability to add prefix\suffix for type names and enum keys
21+
```ts
22+
typePrefix?: string;
23+
typeSuffix?: string;
24+
enumKeyPrefix?: string;
25+
enumKeySuffix?: string;
26+
```
27+
feature: ability to customize resolving process of the extracting type names (`extractingOptions` nodejs option)
28+
```ts
29+
extractingOptions = {
30+
// requestBodySuffix: ["Payload", "Body", "Input"],
31+
// or
32+
// requestBodyNameResolver: (typeName, reservedNames) => string;
33+
34+
// requestParamsSuffix: ["Params"],
35+
// or
36+
// requestParamsNameResolver: (typeName, reservedNames) => string;
37+
38+
// responseBodySuffix: ["Data", "Result", "Output"],
39+
// or
40+
// responseBodyNameResolver: (typeName, reservedNames) => string;
41+
42+
// responseErrorSuffix: ["Error", "Fail", "Fails", "ErrorData", "HttpError", "BadResponse"],
43+
// or
44+
// responseErrorNameResolver: (typeName, reservedNames) => string;
45+
}
46+
```
47+
docs: update docs for `extraTemplates` option
48+
fix: problem with default name of single api file (Api.ts)
49+
fix: problem based with tuple types (#445)
50+
fix: problem with `defaultResponseType` declaration type
51+
52+
353
# 11.1.3
454

555
fix: problems with `text/*` content types (axios, fetch http clients) (thanks @JochenDiekenbrock, #312, #443)
@@ -214,7 +264,7 @@ const primitiveTypes = {
214264
},
215265
array: ({ items, ...schemaPart }, parser) => {
216266
const content = parser.getInlineParseContent(items);
217-
return parser.checkAndAddNull(schemaPart, Ts.ArrayType(content));
267+
return parser.safeAddNullToType(schemaPart, Ts.ArrayType(content));
218268
},
219269
}
220270
```
@@ -456,7 +506,7 @@ Features:
456506
- `--type-suffix` option. Allows to set suffix for data contract name. (issue #191, thanks @the-ult)
457507
- `--type-prefix` option. Allows to set prefix for data contract name. (issue #191, thanks @the-ult)
458508
Examples [here](./spec/typeSuffixPrefix/schema.ts)
459-
- `onFormatTypeName(usageTypeName, rawTypeName)` hook. Allow to format data contract names as you want.
509+
- `onFormatTypeName(usageTypeName, rawTypeName, schemaType)` hook. Allow to format data contract names as you want.
460510

461511
Internal:
462512
- rename and split `checkAndRenameModelName` -> `formatModelName`, `fixModelName`

README.md

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -76,11 +76,12 @@ Options:
7676
--type-prefix <string> data contract name prefix (default: "")
7777
--type-suffix <string> data contract name suffix (default: "")
7878
--clean-output clean output folder before generate api. WARNING: May cause data loss (default: false)
79-
--api-class-name <string> name of the api class
79+
--api-class-name <string> name of the api class (default: "Api")
8080
--patch fix up small errors in the swagger source definition (default: false)
8181
--debug additional information about processes inside this tool (default: false)
8282
--another-array-type generate array types as Array<Type> (by default Type[]) (default: false)
8383
--sort-types sort fields and types (default: false)
84+
--extract-enums extract all enums from inline interface\type content to typescript enum construction (default: false)
8485
-h, --help display help for command
8586
8687
Commands:
@@ -144,9 +145,20 @@ generateApi({
144145
generateUnionEnums: false,
145146
typePrefix: '',
146147
typeSuffix: '',
148+
enumKeyPrefix: '',
149+
enumKeySuffix: '',
147150
addReadonly: false,
151+
extractingOptions: {
152+
requestBodySuffix: ["Payload", "Body", "Input"],
153+
requestParamsSuffix: ["Params"],
154+
responseBodySuffix: ["Data", "Result", "Output"],
155+
responseErrorSuffix: ["Error", "Fail", "Fails", "ErrorData", "HttpError", "BadResponse"],
156+
},
157+
/** allow to generate extra files based with this extra templates, see more below */
148158
extraTemplates: [],
149-
anotherArrayType: false,
159+
anotherArrayType: false,
160+
fixInvalidTypeNamePrefix: "Type",
161+
fixInvalidEnumKeyPrefix: "Value",
150162
codeGenConstructs: (constructs) => ({
151163
...constructs,
152164
RecordType: (key, value) => `MyRecord<key, value>`
@@ -163,8 +175,9 @@ generateApi({
163175
onCreateRoute: (routeData) => {},
164176
onCreateRouteName: (routeNameInfo, rawRouteInfo) => {},
165177
onFormatRouteName: (routeInfo, templateRouteName) => {},
166-
onFormatTypeName: (typeName, rawTypeName) => {},
178+
onFormatTypeName: (typeName, rawTypeName, schemaType) => {},
167179
onInit: (configuration) => {},
180+
onPreParseSchema: (originalSchema, typeName, schemaType) => {},
168181
onParseSchema: (originalSchema, parsedSchema) => {},
169182
onPrepareConfig: (currentConfiguration) => {},
170183
}
@@ -245,8 +258,13 @@ with `--module-name-index 0` Api class will have one property `api`
245258
When we change it to `--module-name-index 1` then Api class have two properties `fruits` and `vegetables`
246259

247260
### **`--module-name-first-tag`**
248-
This option will group your API operations based on their first tag - mirroring how the Swagger UI groups displayed operations
261+
This option will group your API operations based on their first tag - mirroring how the Swagger UI groups displayed operations
249262

263+
### `extraTemplates` (NodeJS option)
264+
type `(Record<string, any> & { name: string, path: string })[]`
265+
This thing allow you to generate extra ts\js files based on extra templates (one extra template for one ts\js file)
266+
[Example here](https://github.com/acacode/swagger-typescript-api/tree/next/tests/spec/extra-templates)
267+
250268

251269
## `generate-templates` command
252270
This command allows you to generate source templates which using with option `--templates`
@@ -433,7 +451,7 @@ generateApi({
433451
},
434452
array: (schema, parser) => {
435453
const content = parser.getInlineParseContent(schema.items);
436-
return parser.checkAndAddNull(schema, `(${content})[]`);
454+
return parser.safeAddNullToType(schema, `(${content})[]`);
437455
},
438456
})
439457
})

index.d.ts

Lines changed: 66 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ interface GenerateApiParamsBase {
106106
/**
107107
* default type for empty response schema (default: "void")
108108
*/
109-
defaultResponseType?: boolean;
109+
defaultResponseType?: string;
110110
/**
111111
* Ability to send HttpClient instance to Api constructor
112112
*/
@@ -136,6 +136,22 @@ interface GenerateApiParamsBase {
136136
primitiveTypeConstructs?: (struct: PrimitiveTypeStruct) => Partial<PrimitiveTypeStruct>;
137137

138138
codeGenConstructs?: (struct: CodeGenConstruct) => Partial<CodeGenConstruct>;
139+
140+
/** extract all enums from nested types\interfaces to `enum` construction */
141+
extractEnums?: boolean;
142+
/** prefix string value needed to fix invalid type names (default: 'Type') */
143+
fixInvalidTypeNamePrefix?: string;
144+
/** prefix string value needed to fix invalid enum keys (default: 'Value') */
145+
fixInvalidEnumKeyPrefix?: string;
146+
/** prefix string value for enum keys */
147+
enumKeyPrefix?: string;
148+
/** suffix string value for enum keys */
149+
enumKeySuffix?: string;
150+
/** prefix string value for type names */
151+
typePrefix?: string;
152+
/** suffix string value for type names */
153+
typeSuffix?: string;
154+
extractingOptions?: Partial<ExtractingOptions>;
139155
}
140156

141157
type CodeGenConstruct = {
@@ -212,9 +228,39 @@ interface GenerateApiParamsFromSpecLiteral extends GenerateApiParamsBase {
212228

213229
export type GenerateApiParams = GenerateApiParamsFromPath | GenerateApiParamsFromUrl | GenerateApiParamsFromSpecLiteral;
214230

231+
type BuildRouteParam = {
232+
/** {bar} */
233+
$match: string;
234+
name: string;
235+
required: boolean;
236+
type: "string";
237+
description: string;
238+
schema: {
239+
type: string;
240+
};
241+
in: "path" | "query";
242+
};
243+
244+
type BuildRoutePath = {
245+
/** /foo/{bar}/baz */
246+
originalRoute: string;
247+
/** /foo/${bar}/baz */
248+
route: string;
249+
pathParams: BuildRouteParam[];
250+
queryParams: BuildRouteParam[];
251+
};
252+
215253
export interface Hooks {
254+
/** calls before parse\process route path */
255+
onPreBuildRoutePath: (routePath: string) => string | void;
256+
/** calls after parse\process route path */
257+
onBuildRoutePath: (data: BuildRoutePath) => BuildRoutePath | void;
258+
/** calls before insert path param name into string path interpolation */
259+
onInsertPathParam: (paramName: string, index: number, arr: BuildRouteParam[], resultRoute: string) => string | void;
216260
/** calls after parse schema component */
217261
onCreateComponent: (component: SchemaComponent) => SchemaComponent | void;
262+
/** calls before parse any kind of schema */
263+
onPreParseSchema: (originalSchema: any, typeName: string, schemaType: string) => any;
218264
/** calls after parse any kind of schema */
219265
onParseSchema: (originalSchema: any, parsedSchema: any) => any | void;
220266
/** calls after parse route (return type: customized route (ParsedRoute), nothing change (void), false (ignore this route)) */
@@ -228,7 +274,7 @@ export interface Hooks {
228274
/** customize request params (path params, query params) */
229275
onCreateRequestParams?: (rawType: SchemaComponent["rawTypeData"]) => SchemaComponent["rawTypeData"] | void;
230276
/** customize name of model type */
231-
onFormatTypeName?: (typeName: string, rawTypeName?: string) => string | void;
277+
onFormatTypeName?: (typeName: string, rawTypeName?: string, schemaType?: "type-name" | "enum-key") => string | void;
232278
/** customize name of route (operationId), you can do it with using onCreateRouteName too */
233279
onFormatRouteName?: (routeInfo: RawRouteInfo, templateRouteName: string) => string | void;
234280
}
@@ -376,6 +422,17 @@ export enum SCHEMA_TYPES {
376422

377423
type MAIN_SCHEMA_TYPES = SCHEMA_TYPES.PRIMITIVE | SCHEMA_TYPES.OBJECT | SCHEMA_TYPES.ENUM;
378424

425+
type ExtractingOptions = {
426+
requestBodySuffix: string[];
427+
responseBodySuffix: string[];
428+
responseErrorSuffix: string[];
429+
requestParamsSuffix: string[];
430+
requestBodyNameResolver: (name: string, reservedNames: string) => string | undefined;
431+
responseBodyNameResolver: (name: string, reservedNames: string) => string | undefined;
432+
responseErrorNameResolver: (name: string, reservedNames: string) => string | undefined;
433+
requestParamsNameResolver: (name: string, reservedNames: string) => string | undefined;
434+
};
435+
379436
export interface GenerateApiConfiguration {
380437
apiConfig: {
381438
baseUrl: string;
@@ -411,6 +468,8 @@ export interface GenerateApiConfiguration {
411468
singleHttpClient: boolean;
412469
typePrefix: string;
413470
typeSuffix: string;
471+
enumKeyPrefix: string;
472+
enumKeySuffix: string;
414473
patch: boolean;
415474
cleanOutput: boolean;
416475
debug: boolean;
@@ -420,7 +479,10 @@ export interface GenerateApiConfiguration {
420479
addReadonly: boolean;
421480
extractResponseBody: boolean;
422481
extractResponseError: boolean;
423-
defaultResponseType: boolean;
482+
extractEnums: boolean;
483+
fixInvalidTypeNamePrefix: string;
484+
fixInvalidEnumKeyPrefix: string;
485+
defaultResponseType: string;
424486
toJS: boolean;
425487
disableThrowOnError: boolean;
426488
silent: boolean;
@@ -452,6 +514,7 @@ export interface GenerateApiConfiguration {
452514
routeNameDuplicatesMap: Map<string, string>;
453515
apiClassName: string;
454516
requestOptions?: import("node-fetch").RequestInit;
517+
extractingOptions: ExtractingOptions;
455518
};
456519
modelTypes: ModelType[];
457520
rawModelTypes: SchemaComponent[];

index.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ const program = cli({
3737
{
3838
flags: "-n, --name <string>",
3939
description: "name of output typescript api file",
40-
default: `${codeGenBaseConfig.apiClassName}.ts`,
40+
default: codeGenBaseConfig.fileName,
4141
},
4242
{
4343
flags: "-t, --templates <string>",
@@ -202,6 +202,11 @@ const program = cli({
202202
description: "sort fields and types",
203203
default: codeGenBaseConfig.sortTypes,
204204
},
205+
{
206+
flags: "--extract-enums",
207+
description: "extract all enums from inline interface\\type content to typescript enum construction",
208+
default: codeGenBaseConfig.extractEnums,
209+
},
205210
],
206211
});
207212

0 commit comments

Comments
 (0)