@penkov/swagger-code-gen 1.3.3 → 1.4.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 CHANGED
@@ -10,12 +10,248 @@ 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 {&#39;available&#39; | &#39;pending&#39; | &#39;sold&#39;} status Status values that need to be considered for filter
131
+ * @param {RequestOptions} requestOptions Additional request params
132
+ * @return {ReadonlyArray&lt;Pet&gt;} 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
+ const preProcessed = option(requestOptions.preProcessRequest).map(cb => cb(request)).getOrElseValue(request);
152
+ const resp = await fetch(preProcessed);
153
+ if (resp.ok) {
154
+ const postProcessed = option(requestOptions.postProcessResponse)
155
+ .map(cb => cb(preProcessed, resp))
156
+ .getOrElseValue(resp);
157
+ const json = option(resp.headers.get('content-length'))
158
+ .map(x => parseInt(x))
159
+ .getOrElseValue(0) > 0 ? await postProcessed.json() : null;
160
+ return json as ReadonlyArray<Pet>;
161
+ } else {
162
+ throw resp;
163
+ }
164
+ }
165
+
166
+
167
+ // ...
168
+
169
+
170
+
171
+ // scats wrappers
172
+
173
+ export class OrderDto {
174
+
175
+ constructor(
176
+ readonly id: number,
177
+ readonly petId: number,
178
+ readonly quantity: number,
179
+ readonly shipDate: string,
180
+ readonly status: string,
181
+ readonly complete: boolean,
182
+ ) {}
183
+
184
+
185
+ static fromJson(json: Order): OrderDto {
186
+ return new OrderDto(
187
+ json.id,
188
+ json.petId,
189
+ json.quantity,
190
+ json.shipDate,
191
+ json.status,
192
+ json.complete,
193
+ );
194
+ }
195
+
196
+ copy(fields: Partial<OrderDto>): OrderDto {
197
+ return new OrderDto(
198
+ option(fields.id).getOrElseValue(this.id),
199
+ option(fields.petId).getOrElseValue(this.petId),
200
+ option(fields.quantity).getOrElseValue(this.quantity),
201
+ option(fields.shipDate).getOrElseValue(this.shipDate),
202
+ option(fields.status).getOrElseValue(this.status),
203
+ option(fields.complete).getOrElseValue(this.complete),
204
+ );
205
+ }
206
+
207
+ get toJson(): Order {
208
+ return {
209
+ id: this.id,
210
+ petId: this.petId,
211
+ quantity: this.quantity,
212
+ shipDate: this.shipDate,
213
+ status: this.status,
214
+ complete: this.complete,
215
+ };
216
+ }
217
+ }
218
+
219
+
220
+ export class ApiClient {
221
+
222
+ constructor(private readonly requestOptions: RequestOptions = defaultRequestOptions()) {
223
+ }
224
+
225
+
226
+ async updatePet(
227
+ body: Pet,
228
+ requestOptions: RequestOptions = this.requestOptions
229
+ ): Promise<TryLike<PetDto>> {
230
+ return (await Try.promise(() =>
231
+ updatePet(
232
+ body,
233
+ requestOptions
234
+ )
235
+ ))
236
+ .map(res => PetDto.fromJson(res))
237
+ ;
238
+ }
239
+
240
+ async addPet(
241
+ body: Pet,
242
+ requestOptions: RequestOptions = this.requestOptions
243
+ ): Promise<TryLike<PetDto>> {
244
+ return (await Try.promise(() =>
245
+ addPet(
246
+ body,
247
+ requestOptions
248
+ )
249
+ ))
250
+ .map(res => PetDto.fromJson(res))
251
+ ;
252
+ }
253
+
254
+ //...
255
+ }
256
+
257
+ ```
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
- .option('--url <URI>', 'The url with swagger definitions')
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
  });
@@ -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], ['body', 3]);
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);
@@ -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 {
@@ -34,6 +33,26 @@ export const defaultReqOpts: RequestOptions = {
34
33
 
35
34
  const defaultRequestOptions = () => defaultReqOpts;
36
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
+ }
55
+
37
56
  <% schemas.foreach(schema => { %>
38
57
  <%- include('schema.ejs', {schema: schema}); %>
39
58
  <% }); %>
@@ -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
- ...option(requestOptions.headers).getOrElseValue({}),
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
- const preProcessed = option(requestOptions.preProcessRequest).map(cb => cb(request)).getOrElseValue(request);
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
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@penkov/swagger-code-gen",
3
- "version": "1.3.3",
3
+ "version": "1.4.0",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "generate-client": "./dist/cli.mjs"