@penkov/swagger-code-gen 1.3.3 → 1.5.0
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/README.md +231 -0
- package/dist/cli.mjs +9 -2
- package/dist/components-parse.js +4 -0
- package/dist/method.js +3 -3
- package/dist/templates/index.ejs +23 -4
- package/dist/templates/method.ejs +3 -15
- package/dist/templates/scats-method.ejs +17 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -10,12 +10,243 @@ npm install -D @penkov/swagger-code-gen
|
|
|
10
10
|
Usage:
|
|
11
11
|
```shell
|
|
12
12
|
generate-client --url <URI> output_filename.ts
|
|
13
|
+
generate-client --url <URI> --includeTags tag1 tag2 -- output_filename.ts
|
|
13
14
|
```
|
|
14
15
|
|
|
15
16
|
Cli parameters:
|
|
16
17
|
* `--url <URI>` - the swagger url
|
|
18
|
+
* `--includeTags <tags...>` - Space-separated list of tags of paths to be included. Path is included if it contains any of specified tag
|
|
19
|
+
Path is included if exclusion list is empty or path contains any of the tags from inclusion list.
|
|
20
|
+
If the tag is both in inclusion and exclusion lists, it gets excluded.
|
|
21
|
+
* `--excludeTags <tags...>` - Space-separated list of tags of paths to be excluded.
|
|
22
|
+
Path is excluded if exclusion list is non-empty and path contains any of the tags from exclusion list.
|
|
23
|
+
If the tag is both in inclusion and exclusion lists, it gets excluded.
|
|
17
24
|
* `--referencedObjectsNullableByDefault` - then specified, the generated code will assume that
|
|
18
25
|
any object's field, that references another object, can be null, unless it is explicitly specified to be not nullable
|
|
19
26
|
(which is default in .net world: asp generates wrong spec)
|
|
20
27
|
* `--enableScats` - generate additional wrappers in [scats](https://www.npmjs.com/package/scats)
|
|
21
28
|
style for all objects and create a service with methods for each endpoint.
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# Example of generated code:
|
|
33
|
+
|
|
34
|
+
```shell
|
|
35
|
+
generate-client --enableScats --url https://petstore3.swagger.io/api/v3/openapi.json petstore.ts
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Will generate:
|
|
39
|
+
```typescript
|
|
40
|
+
// header skipped
|
|
41
|
+
|
|
42
|
+
export interface Customer {
|
|
43
|
+
readonly id: number;
|
|
44
|
+
readonly username: string;
|
|
45
|
+
readonly address: ReadonlyArray<Address>;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
export interface Address {
|
|
50
|
+
readonly street: string;
|
|
51
|
+
readonly city: string;
|
|
52
|
+
readonly state: string;
|
|
53
|
+
readonly zip: string;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
export interface Category {
|
|
58
|
+
readonly id: number;
|
|
59
|
+
readonly name: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
export interface User {
|
|
64
|
+
readonly id: number;
|
|
65
|
+
readonly username: string;
|
|
66
|
+
readonly firstName: string;
|
|
67
|
+
readonly lastName: string;
|
|
68
|
+
readonly email: string;
|
|
69
|
+
readonly password: string;
|
|
70
|
+
readonly phone: string;
|
|
71
|
+
readonly userStatus: number;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
export interface Tag {
|
|
76
|
+
readonly id: number;
|
|
77
|
+
readonly name: string;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
export interface Pet {
|
|
82
|
+
readonly id: number;
|
|
83
|
+
readonly name: string;
|
|
84
|
+
readonly category: Category;
|
|
85
|
+
readonly photoUrls: ReadonlyArray<string>;
|
|
86
|
+
readonly tags: ReadonlyArray<Tag>;
|
|
87
|
+
readonly status: string;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
export interface ApiResponse {
|
|
92
|
+
readonly code: number;
|
|
93
|
+
readonly type: string;
|
|
94
|
+
readonly message: string;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* PUT /pet
|
|
101
|
+
* @summary Update an existing pet
|
|
102
|
+
* @description Update an existing pet by Id
|
|
103
|
+
* @param {Pet} body Update an existent pet in the store
|
|
104
|
+
* @param {RequestOptions} requestOptions Additional request params
|
|
105
|
+
* @return {Pet} Successful operation
|
|
106
|
+
*/
|
|
107
|
+
export async function updatePet(
|
|
108
|
+
body: Pet,
|
|
109
|
+
requestOptions: RequestOptions = defaultRequestOptions()
|
|
110
|
+
): Promise<Pet> {
|
|
111
|
+
let query = '';
|
|
112
|
+
const request = new Request(`${requestOptions.apiPrefix}/pet${query}`, {
|
|
113
|
+
method: 'put',
|
|
114
|
+
body: JSON.stringify(body),
|
|
115
|
+
headers: {
|
|
116
|
+
...option(requestOptions.headers).getOrElseValue({}),
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
return requestImpl<Pet>(request, requestOptions);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
// ...
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* GET /pet/findByStatus
|
|
128
|
+
* @summary Finds Pets by status
|
|
129
|
+
* @description Multiple status values can be provided with comma separated strings
|
|
130
|
+
* @param {'available' | 'pending' | 'sold'} status Status values that need to be considered for filter
|
|
131
|
+
* @param {RequestOptions} requestOptions Additional request params
|
|
132
|
+
* @return {ReadonlyArray<Pet>} successful operation
|
|
133
|
+
*/
|
|
134
|
+
export async function findPetsByStatus(
|
|
135
|
+
status: 'available' | 'pending' | 'sold' = 'available',
|
|
136
|
+
requestOptions: RequestOptions = defaultRequestOptions()
|
|
137
|
+
): Promise<ReadonlyArray<Pet>> {
|
|
138
|
+
let query = '';
|
|
139
|
+
const queryParams = [];
|
|
140
|
+
queryParams.push(`status=${status}`);
|
|
141
|
+
if (queryParams.length > 0) {
|
|
142
|
+
query = '?' + queryParams.join('&');
|
|
143
|
+
}
|
|
144
|
+
const request = new Request(`${requestOptions.apiPrefix}/pet/findByStatus${query}`, {
|
|
145
|
+
method: 'get',
|
|
146
|
+
body: undefined,
|
|
147
|
+
headers: {
|
|
148
|
+
...option(requestOptions.headers).getOrElseValue({}),
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
return requestImpl<Pet>(request, requestOptions);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
// ...
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
// scats wrappers
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
export class PetDto {
|
|
163
|
+
|
|
164
|
+
constructor(
|
|
165
|
+
readonly id: number,
|
|
166
|
+
readonly name: string,
|
|
167
|
+
readonly category: CategoryDto,
|
|
168
|
+
readonly photoUrls: Collection<string>,
|
|
169
|
+
readonly tags: Collection<TagDto>,
|
|
170
|
+
readonly status: string,
|
|
171
|
+
) {}
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
static fromJson(json: Pet): PetDto {
|
|
175
|
+
return new PetDto(
|
|
176
|
+
json.id,
|
|
177
|
+
json.name,
|
|
178
|
+
CategoryDto.fromJson(json.category),
|
|
179
|
+
Collection.from(option(json.photoUrls).getOrElseValue([]))
|
|
180
|
+
,
|
|
181
|
+
Collection.from(option(json.tags).getOrElseValue([]))
|
|
182
|
+
.map(i => TagDto.fromJson(i)),
|
|
183
|
+
json.status,
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
copy(fields: Partial<PetDto>): PetDto {
|
|
188
|
+
return new PetDto(
|
|
189
|
+
option(fields.id).getOrElseValue(this.id),
|
|
190
|
+
option(fields.name).getOrElseValue(this.name),
|
|
191
|
+
option(fields.category).getOrElseValue(this.category),
|
|
192
|
+
option(fields.photoUrls).getOrElseValue(this.photoUrls),
|
|
193
|
+
option(fields.tags).getOrElseValue(this.tags),
|
|
194
|
+
option(fields.status).getOrElseValue(this.status),
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
get toJson(): Pet {
|
|
199
|
+
return {
|
|
200
|
+
id: this.id,
|
|
201
|
+
name: this.name,
|
|
202
|
+
category: this.category.toJson,
|
|
203
|
+
photoUrls: this.photoUrls
|
|
204
|
+
.toArray,
|
|
205
|
+
tags: this.tags
|
|
206
|
+
.map(_ => _.toJson) .toArray,
|
|
207
|
+
status: this.status,
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
export class ApiClient {
|
|
214
|
+
|
|
215
|
+
constructor(private readonly requestOptions: RequestOptions = defaultRequestOptions()) {
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// ... some methods skipped
|
|
219
|
+
|
|
220
|
+
async updatePet(
|
|
221
|
+
body: PetDto,
|
|
222
|
+
requestOptions: RequestOptions = this.requestOptions
|
|
223
|
+
): Promise<TryLike<PetDto>> {
|
|
224
|
+
return (await Try.promise(() =>
|
|
225
|
+
updatePet(
|
|
226
|
+
body.toJson,
|
|
227
|
+
requestOptions
|
|
228
|
+
)
|
|
229
|
+
))
|
|
230
|
+
.map(res => PetDto.fromJson(res))
|
|
231
|
+
;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
async findPetsByStatus(
|
|
235
|
+
status: 'available' | 'pending' | 'sold',
|
|
236
|
+
requestOptions: RequestOptions = this.requestOptions
|
|
237
|
+
): Promise<TryLike<Collection<PetDto>>> {
|
|
238
|
+
return (await Try.promise(() =>
|
|
239
|
+
findPetsByStatus(
|
|
240
|
+
status,
|
|
241
|
+
requestOptions
|
|
242
|
+
)
|
|
243
|
+
))
|
|
244
|
+
.map(res => Collection.from(option(res).getOrElseValue([])))
|
|
245
|
+
.map(items => items.map(i => PetDto.fromJson(i)))
|
|
246
|
+
;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
//...
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
```
|
package/dist/cli.mjs
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { main } from './index.js';
|
|
3
3
|
import { Command } from "commander";
|
|
4
|
+
import { HashSet } from "scats";
|
|
4
5
|
const program = new Command();
|
|
5
6
|
program
|
|
6
7
|
.name('Swagger client code generator')
|
|
7
8
|
.description('CLI to generate client based on swagger definitions')
|
|
8
9
|
.version('1.0.0')
|
|
9
|
-
.
|
|
10
|
+
.requiredOption('--url <URI>', 'The url with swagger definitions')
|
|
10
11
|
.option('--referencedObjectsNullableByDefault', 'Assume that referenced objects can be null (say hello to .net assholes)', false)
|
|
12
|
+
.option('--includeTags <tags...>', 'Space-separated list of tags of paths to be included. Path is included if it contains any of specified tag')
|
|
13
|
+
.option('--excludeTags <tags...>', 'Space-separated list of tags of paths to be excluded. Path is excluded if it contains any of specified tag')
|
|
11
14
|
.option('--enableScats', 'Generate scats', false)
|
|
12
15
|
.argument('outputFile', 'File with generated code')
|
|
13
16
|
.parse();
|
|
@@ -15,7 +18,11 @@ const url = program.opts().url;
|
|
|
15
18
|
const referencedObjectsNullableByDefault = program.opts().referencedObjectsNullableByDefault;
|
|
16
19
|
const enableScats = program.opts().enableScats;
|
|
17
20
|
const outputFile = program.args[0];
|
|
21
|
+
const includeTags = HashSet.from(program.opts().includeTags || []);
|
|
22
|
+
const excludeTags = HashSet.from(program.opts().excludeTags || []);
|
|
18
23
|
main(url, enableScats, outputFile, {
|
|
19
|
-
referencedObjectsNullableByDefault: referencedObjectsNullableByDefault
|
|
24
|
+
referencedObjectsNullableByDefault: referencedObjectsNullableByDefault,
|
|
25
|
+
includeTags: includeTags,
|
|
26
|
+
excludeTags: excludeTags
|
|
20
27
|
}).then(() => {
|
|
21
28
|
});
|
package/dist/components-parse.js
CHANGED
|
@@ -17,5 +17,9 @@ export function resolvePaths(json, schemasTypes, options) {
|
|
|
17
17
|
return Collection.from(Object.keys(jsonSchemas)).flatMap(path => {
|
|
18
18
|
const methods = jsonSchemas[path];
|
|
19
19
|
return Collection.from(Object.keys(methods)).map(methodName => new Method(path, methodName, methods[methodName], schemasTypes, options));
|
|
20
|
+
}).filter(m => {
|
|
21
|
+
const included = options.includeTags.isEmpty || options.includeTags.intersect(m.tags).nonEmpty;
|
|
22
|
+
const excluded = options.excludeTags.nonEmpty && options.excludeTags.intersect(m.tags).nonEmpty;
|
|
23
|
+
return included && !excluded;
|
|
20
24
|
});
|
|
21
25
|
}
|
package/dist/method.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { Collection, HashMap, identity, option } from 'scats';
|
|
1
|
+
import { Collection, HashMap, HashSet, identity, option } from 'scats';
|
|
2
2
|
import { Property } from './property.js';
|
|
3
3
|
import { Parameter } from './parameter.js';
|
|
4
4
|
import { SchemaFactory } from './schemas.js';
|
|
5
|
-
const sortByIn = HashMap.of(['path', 0], ['query', 1], ['header', 2], ['
|
|
5
|
+
const sortByIn = HashMap.of(['path', 0], ['query', 1], ['header', 2], ['cookie', 3], ['body', 4]);
|
|
6
6
|
export class Method {
|
|
7
7
|
constructor(path, method, def, schemasTypes, options) {
|
|
8
8
|
this.path = path;
|
|
9
9
|
this.method = method;
|
|
10
|
-
this.tags = option(def.tags).getOrElseValue([]);
|
|
10
|
+
this.tags = HashSet.from(option(def.tags).getOrElseValue([]));
|
|
11
11
|
this.summary = def.summary;
|
|
12
12
|
this.description = def.description;
|
|
13
13
|
this.operationId = option(def.operationId);
|
package/dist/templates/index.ejs
CHANGED
|
@@ -11,9 +11,8 @@
|
|
|
11
11
|
*********************************************************
|
|
12
12
|
*********************************************************/
|
|
13
13
|
import fetch, {Request, Response} from 'node-fetch';
|
|
14
|
-
import {option, Option} from 'scats';
|
|
15
14
|
<% if (scats) {%>
|
|
16
|
-
import {Collection, Try, TryLike, none} from 'scats';
|
|
15
|
+
import {option, Option, Collection, Try, TryLike, none} from 'scats';
|
|
17
16
|
<% } %>
|
|
18
17
|
|
|
19
18
|
export interface RequestOptions {
|
|
@@ -24,7 +23,7 @@ export interface RequestOptions {
|
|
|
24
23
|
}
|
|
25
24
|
|
|
26
25
|
|
|
27
|
-
export const
|
|
26
|
+
export const defaultRequestOptions: RequestOptions = {
|
|
28
27
|
apiPrefix: '',
|
|
29
28
|
headers: {
|
|
30
29
|
'Accept': 'application/json',
|
|
@@ -32,7 +31,27 @@ export const defaultReqOpts: RequestOptions = {
|
|
|
32
31
|
}
|
|
33
32
|
};
|
|
34
33
|
|
|
35
|
-
const
|
|
34
|
+
const defReqOpts = () => defaultRequestOptions;
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
async function requestImpl<T>(request: Request, requestOptions: RequestOptions): Promise<T> {
|
|
38
|
+
const preProcessed = requestOptions.preProcessRequest ? requestOptions.preProcessRequest(request) : request;
|
|
39
|
+
const resp = await fetch(preProcessed);
|
|
40
|
+
if (resp.ok) {
|
|
41
|
+
const postProcessed = requestOptions.postProcessResponse ? requestOptions.postProcessResponse(preProcessed, resp) : resp;
|
|
42
|
+
let json: any = null;
|
|
43
|
+
if (postProcessed.headers.has('content-length')) {
|
|
44
|
+
const ct = parseInt(postProcessed.headers.get('content-length'));
|
|
45
|
+
if (ct > 0) {
|
|
46
|
+
json = await postProcessed.json()
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return json as T;
|
|
50
|
+
} else {
|
|
51
|
+
throw resp;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
}
|
|
36
55
|
|
|
37
56
|
<% schemas.foreach(schema => { %>
|
|
38
57
|
<%- include('schema.ejs', {schema: schema}); %>
|
|
@@ -33,7 +33,7 @@ export async function <%= method.endpointName %>(
|
|
|
33
33
|
<%_ if (method.body.nonEmpty) { -%>
|
|
34
34
|
body: <%- method.body.get.jsType %>,
|
|
35
35
|
<%_ } -%>
|
|
36
|
-
requestOptions: RequestOptions =
|
|
36
|
+
requestOptions: RequestOptions = defReqOpts()
|
|
37
37
|
): Promise<<%- method.response.responseType %>> {
|
|
38
38
|
let query = '';
|
|
39
39
|
<%_ if (method.parameters.filter(x => x.in === 'query').nonEmpty) { -%>
|
|
@@ -62,7 +62,7 @@ export async function <%= method.endpointName %>(
|
|
|
62
62
|
method: '<%= method.method %>',
|
|
63
63
|
body: <%= method.body.map(() => 'JSON.stringify(body)').getOrElseValue('undefined') %>,
|
|
64
64
|
headers: {
|
|
65
|
-
...
|
|
65
|
+
...requestOptions.headers || {},
|
|
66
66
|
<%_ if (method.parameters.filter(x => x.in === 'header').nonEmpty) { -%>
|
|
67
67
|
<%_ method.parameters.filter(x => x.in === 'header').foreach(p => { -%>
|
|
68
68
|
<%= p.name %>: <%= method.wrapParamsInObject ? 'params.' : '' %><%= p.uniqueName %>
|
|
@@ -70,17 +70,5 @@ export async function <%= method.endpointName %>(
|
|
|
70
70
|
<%_ } -%>
|
|
71
71
|
}
|
|
72
72
|
});
|
|
73
|
-
|
|
74
|
-
const resp = await fetch(preProcessed);
|
|
75
|
-
if (resp.ok) {
|
|
76
|
-
const postProcessed = option(requestOptions.postProcessResponse)
|
|
77
|
-
.map(cb => cb(preProcessed, resp))
|
|
78
|
-
.getOrElseValue(resp);
|
|
79
|
-
const json = option(resp.headers.get('content-length'))
|
|
80
|
-
.map(x => parseInt(x))
|
|
81
|
-
.getOrElseValue(0) > 0 ? await postProcessed.json() : null;
|
|
82
|
-
return json as <%- method.response.responseType %>;
|
|
83
|
-
} else {
|
|
84
|
-
throw resp;
|
|
85
|
-
}
|
|
73
|
+
return requestImpl<<%- method.response.responseType %>>(request, requestOptions);
|
|
86
74
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export class ApiClient {
|
|
2
2
|
|
|
3
|
-
constructor(private readonly requestOptions: RequestOptions =
|
|
3
|
+
constructor(private readonly requestOptions: RequestOptions = defReqOpts()) {
|
|
4
4
|
}
|
|
5
5
|
|
|
6
6
|
|
|
@@ -18,7 +18,7 @@ export class ApiClient {
|
|
|
18
18
|
},
|
|
19
19
|
<%_ } -%>
|
|
20
20
|
<%_ method.body.foreach(body => { -%>
|
|
21
|
-
body: <%- body.
|
|
21
|
+
body: <%- body.scatsWrapperType %>,
|
|
22
22
|
<%_ }); -%>
|
|
23
23
|
requestOptions: RequestOptions = this.requestOptions
|
|
24
24
|
): Promise<TryLike<<%- method.response.asProperty.scatsWrapperType %>>> {
|
|
@@ -31,9 +31,23 @@ export class ApiClient {
|
|
|
31
31
|
<%_ } else { -%>
|
|
32
32
|
params,
|
|
33
33
|
<%_ } -%>
|
|
34
|
-
<%_
|
|
34
|
+
<%_ method.body.foreach(body => { -%>
|
|
35
|
+
<%_ if (body.schemaType === 'object') { _%>
|
|
36
|
+
body.toJson,
|
|
37
|
+
<%_ } else if (body.schemaType === 'property') { _%>
|
|
38
|
+
<%_ if (body.isArray && body.itemReferencesObject) { _%>
|
|
39
|
+
body.map(_ => _.toJson).toArray,
|
|
40
|
+
<%_ } else if (body.isArray && !body.itemReferencesObject) { -%>
|
|
41
|
+
body.toArray,
|
|
42
|
+
<%_ } else if (body.referencesObject) { -%>
|
|
43
|
+
body.toJson,
|
|
44
|
+
<%_ } else { -%>
|
|
45
|
+
body,
|
|
46
|
+
<%_ } -%>
|
|
47
|
+
<%_ } else { -%>
|
|
35
48
|
body,
|
|
36
49
|
<%_ } -%>
|
|
50
|
+
<%_ }); -%>
|
|
37
51
|
requestOptions
|
|
38
52
|
)
|
|
39
53
|
))
|