@penkov/swagger-code-gen 1.3.2 → 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,15 +1,17 @@
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
- const parameters = Collection.from(def.parameters)
12
+ this.description = def.description;
13
+ this.operationId = option(def.operationId);
14
+ const parameters = Collection.from(option(def.parameters).getOrElseValue([]))
13
15
  .map(p => Parameter.fromDefinition(p, schemasTypes, options))
14
16
  .sort((a, b) => {
15
17
  const r1 = a.required ? 1 : 0;
@@ -41,12 +43,15 @@ export class Method {
41
43
  .orElseValue(mimeTypes.headOption)
42
44
  .map(mt => SchemaFactory.build('body', body[mt].schema, schemasTypes, options));
43
45
  });
46
+ this.bodyDescription = option(def.requestBody).flatMap(body => option(body.description));
44
47
  const statusCodes = Collection.from(Object.keys(def.responses))
45
48
  .map(x => parseInt(x));
46
49
  const successCode = statusCodes
47
50
  .filter(code => code / 100 === 2)
48
51
  .minByOption(identity);
49
- const respDef = successCode.map(_ => def.responses[_]).getOrElseValue(def.responses[statusCodes.head]);
52
+ const respDef = successCode.map(_ => def.responses[_])
53
+ .orElse(() => option(def.responses['default']))
54
+ .getOrElseValue(def.responses[statusCodes.head]);
50
55
  const mimeTypes = option(respDef.content)
51
56
  .map(content => Collection.from(Object.keys(content)).toMap(mimeType => [mimeType, content[mimeType]])).getOrElseValue(HashMap.empty);
52
57
  this.response = mimeTypes.get('application/json')
@@ -63,12 +68,13 @@ export class Method {
63
68
  asProperty: Property.fromDefinition('UNKNOWN', { type: 'any' }, schemasTypes, options),
64
69
  responseType: 'any'
65
70
  }));
71
+ this.wrapParamsInObject = this.parameters.size > 2 || (this.body.isDefined) && this.parameters.nonEmpty;
66
72
  }
67
73
  get endpointName() {
68
- return `${this.method}${Method.pathToName(this.path)}`;
74
+ return this.operationId.getOrElse(() => `${this.method}${Method.pathToName(this.path)}`);
69
75
  }
70
76
  get pathWithSubstitutions() {
71
- const paramPrefix = `${this.parameters.size > 2 ? 'params.' : ''}`;
77
+ const paramPrefix = `${this.wrapParamsInObject ? 'params.' : ''}`;
72
78
  return this.path.replace(/\{(\w+?)\}/g, (matched, group) => {
73
79
  const remappedName = this.parameters.find(p => p.name === group && p.in === 'path')
74
80
  .map(_ => _.uniqueName)
package/dist/parameter.js CHANGED
@@ -1,13 +1,14 @@
1
1
  import { SchemaEnum, SchemaFactory, SchemaObject } from './schemas.js';
2
- import { Collection, identity, option } from 'scats';
2
+ import { Collection, identity, none, option } from 'scats';
3
3
  import { Method } from './method.js';
4
4
  import { Property } from './property.js';
5
5
  export class Parameter {
6
- constructor(name, uniqueName, inValue, jsType, required, description) {
6
+ constructor(name, uniqueName, inValue, jsType, required, defaultValue, description) {
7
7
  this.name = name;
8
8
  this.uniqueName = uniqueName;
9
9
  this.jsType = jsType;
10
10
  this.required = required;
11
+ this.defaultValue = defaultValue;
11
12
  this.description = description;
12
13
  this.in = inValue;
13
14
  }
@@ -15,14 +16,33 @@ export class Parameter {
15
16
  const name = Parameter.toJSName(def.name);
16
17
  const inValue = def.in;
17
18
  const desc = option(def.description);
18
- const required = option(def.required).exists(identity);
19
+ let defaultValue = none;
19
20
  const schema = SchemaFactory.build(def.name, def.schema, schemas, options);
20
21
  let jsType;
21
22
  if (schema instanceof SchemaObject) {
22
23
  jsType = schema.type;
23
24
  }
24
25
  else if (schema instanceof SchemaEnum) {
25
- jsType = schema.name;
26
+ if (schemas.containsKey(schema.name)) {
27
+ jsType = schema.name;
28
+ }
29
+ else if (schema.type === 'string') {
30
+ jsType = `${schema.values.map(x => `'${x}'`).mkString(' | ')}`;
31
+ }
32
+ else if (schema.type === 'integer') {
33
+ jsType = `${schema.values.map(x => `${x}`).mkString(' | ')}`;
34
+ }
35
+ else {
36
+ jsType = schema.type;
37
+ }
38
+ defaultValue = schema.defaultValue.map(x => {
39
+ if (schema.type === 'string') {
40
+ return `'${x}'`;
41
+ }
42
+ else {
43
+ return x;
44
+ }
45
+ });
26
46
  }
27
47
  else if (schema instanceof Property) {
28
48
  jsType = schema.jsType;
@@ -30,7 +50,8 @@ export class Parameter {
30
50
  else {
31
51
  throw new Error('Unknown schema type');
32
52
  }
33
- return new Parameter(name, name, inValue, jsType, required, desc);
53
+ const required = option(def.required).exists(identity) || defaultValue.nonEmpty;
54
+ return new Parameter(name, name, inValue, jsType, required, defaultValue, desc);
34
55
  }
35
56
  static toJSName(path) {
36
57
  const tokens = Collection.from(path.split(/\W/)).filter(t => t.length > 0);
@@ -39,6 +60,6 @@ export class Parameter {
39
60
  }).mkString();
40
61
  }
41
62
  copy(p) {
42
- return new Parameter(option(p.name).getOrElseValue(this.name), option(p.uniqueName).getOrElseValue(this.uniqueName), option(p.in).getOrElseValue(this.in), option(p.jsType).getOrElseValue(this.jsType), option(p.required).getOrElseValue(this.required), option(p.description).getOrElseValue(this.description));
63
+ return new Parameter(option(p.name).getOrElseValue(this.name), option(p.uniqueName).getOrElseValue(this.uniqueName), option(p.in).getOrElseValue(this.in), option(p.jsType).getOrElseValue(this.jsType), option(p.required).getOrElseValue(this.required), option(p.defaultValue).getOrElseValue(this.defaultValue), option(p.description).getOrElseValue(this.description));
43
64
  }
44
65
  }
package/dist/schemas.js CHANGED
@@ -37,15 +37,16 @@ export class SchemaFactory {
37
37
  }
38
38
  }
39
39
  export class SchemaEnum {
40
- constructor(name, title, type, values) {
40
+ constructor(name, title, type, defaultValue, values) {
41
41
  this.name = name;
42
42
  this.title = title;
43
43
  this.type = type;
44
+ this.defaultValue = defaultValue;
44
45
  this.values = values;
45
46
  this.schemaType = 'enum';
46
47
  }
47
48
  static fromDefinition(name, def) {
48
- return new SchemaEnum(name, def.title, def.type, option(def.enum).map(Collection.from).getOrElseValue(Nil));
49
+ return new SchemaEnum(name, def.title, def.type, option(def.default), option(def.enum).map(Collection.from).getOrElseValue(Nil));
49
50
  }
50
51
  }
51
52
  export class SchemaObject {
@@ -33,6 +33,26 @@ export const defaultReqOpts: RequestOptions = {
33
33
 
34
34
  const defaultRequestOptions = () => defaultReqOpts;
35
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
+
36
56
  <% schemas.foreach(schema => { %>
37
57
  <%- include('schema.ejs', {schema: schema}); %>
38
58
  <% }); %>
@@ -1,22 +1,27 @@
1
1
  /**
2
2
  * <%= method.method.toUpperCase() %> <%= method.path %>
3
- <% if (method.parameters.size > 2) { -%>
3
+ <% if (method.summary) { -%>
4
+ * @summary <%= method.summary %>
5
+ <% } -%>
6
+ <% if (method.description) { -%>
7
+ * @description <%= method.description %>
8
+ <% } -%>
9
+ <% if (method.wrapParamsInObject) { -%>
4
10
  * @param {Object} params
5
11
  <% } -%>
6
12
  <% method.parameters.foreach(p => { -%>
7
- * @param {<%= p.jsType %>} <%= method.parameters.size > 2 ? 'params.' : '' %><%= p.uniqueName %> <%= p.description.getOrElseValue('')%>
13
+ * @param {<%= p.jsType %>} <%= method.wrapParamsInObject ? 'params.' : '' %><%= p.uniqueName %> <%= p.description.getOrElseValue('')%>
8
14
  <% }); -%>
9
15
  <%_ if (method.body.nonEmpty) { -%>
10
- * @param {<%= method.body.get.type %>} body
16
+ * @param {<%= method.body.get.jsType %>} body <%= method.bodyDescription.getOrElseValue('') %>
11
17
  <%_ } -%>
12
18
  * @param {RequestOptions} requestOptions Additional request params
13
- * @summary <%= method.summary %>
14
19
  * @return {<%= method.response.responseType %>} <%= method.response.description %>
15
20
  */
16
21
  export async function <%= method.endpointName %>(
17
- <%_ if (method.parameters.size <= 2) { -%>
22
+ <%_ if (!method.wrapParamsInObject) { -%>
18
23
  <%_ method.parameters.foreach(p => { -%>
19
- <%= p.uniqueName %><%= p.required ? '' : '?'%>: <%- p.jsType %>,
24
+ <%= p.uniqueName %><%= p.required ? '' : '?'%>: <%- p.jsType %><%- p.defaultValue.map(x => ` = ${x}`).getOrElseValue('') %>,
20
25
  <%_ }) -%>
21
26
  <%_ } else { -%>
22
27
  params: {
@@ -26,7 +31,7 @@ export async function <%= method.endpointName %>(
26
31
  },
27
32
  <%_ } -%>
28
33
  <%_ if (method.body.nonEmpty) { -%>
29
- body: <%= method.body.get.type %>,
34
+ body: <%- method.body.get.jsType %>,
30
35
  <%_ } -%>
31
36
  requestOptions: RequestOptions = defaultRequestOptions()
32
37
  ): Promise<<%- method.response.responseType %>> {
@@ -35,17 +40,17 @@ export async function <%= method.endpointName %>(
35
40
  const queryParams = [];
36
41
  <%_ method.parameters.filter(x => x.in === 'query' && x.required).foreach(p => { -%>
37
42
  <%_ if (p.jsType === 'string') { -%>
38
- queryParams.push(`<%= p.name %>=${encodeURIComponent(<%= method.parameters.size > 2 ? 'params.' : '' %><%= p.uniqueName %>)}`);
43
+ queryParams.push(`<%= p.name %>=${encodeURIComponent(<%= method.wrapParamsInObject ? 'params.' : '' %><%= p.uniqueName %>)}`);
39
44
  <%_ } else { -%>
40
- queryParams.push(`<%= p.name %>=${<%= method.parameters.size > 2 ? 'params.' : '' %><%= p.uniqueName %>}`);
45
+ queryParams.push(`<%= p.name %>=${<%= method.wrapParamsInObject ? 'params.' : '' %><%= p.uniqueName %>}`);
41
46
  <%_ } -%>
42
47
  <%_ }) -%>
43
48
  <%_ method.parameters.filter(x => x.in === 'query' && !x.required).foreach(p => { -%>
44
- if (!!<%= method.parameters.size > 2 ? 'params.' : '' %><%= p.uniqueName %>) {
49
+ if (!!<%= method.wrapParamsInObject ? 'params.' : '' %><%= p.uniqueName %>) {
45
50
  <%_ if (p.jsType === 'string') { -%>
46
- queryParams.push(`<%= p.name %>=${encodeURIComponent(<%= method.parameters.size > 2 ? 'params.' : '' %><%= p.uniqueName %>)}`);
51
+ queryParams.push(`<%= p.name %>=${encodeURIComponent(<%= method.wrapParamsInObject ? 'params.' : '' %><%= p.uniqueName %>)}`);
47
52
  <%_ } else { -%>
48
- queryParams.push(`<%= p.name %>=${<%= method.parameters.size > 2 ? 'params.' : '' %><%= p.uniqueName %>}`);
53
+ queryParams.push(`<%= p.name %>=${<%= method.wrapParamsInObject ? 'params.' : '' %><%= p.uniqueName %>}`);
49
54
  <%_ } -%>
50
55
  }
51
56
  <%_ }) -%>
@@ -57,25 +62,13 @@ export async function <%= method.endpointName %>(
57
62
  method: '<%= method.method %>',
58
63
  body: <%= method.body.map(() => 'JSON.stringify(body)').getOrElseValue('undefined') %>,
59
64
  headers: {
60
- ...option(requestOptions.headers).getOrElseValue({}),
65
+ ...requestOptions.headers || {},
61
66
  <%_ if (method.parameters.filter(x => x.in === 'header').nonEmpty) { -%>
62
67
  <%_ method.parameters.filter(x => x.in === 'header').foreach(p => { -%>
63
- <%= p.name %>: <%= method.parameters.size > 2 ? 'params.' : '' %><%= p.uniqueName %>
68
+ <%= p.name %>: <%= method.wrapParamsInObject ? 'params.' : '' %><%= p.uniqueName %>
64
69
  <%_ }) -%>
65
70
  <%_ } -%>
66
71
  }
67
72
  });
68
- const preprocessed = option(requestOptions.preProcessRequest).map(cb => cb(request)).getOrElseValue(request);
69
- const resp = await fetch(preprocessed);
70
- if (resp.ok) {
71
- const postprocessed = option(requestOptions.postProcessResponse)
72
- .map(cb => cb(preprocessed, resp))
73
- .getOrElseValue(resp);
74
- const json = option(resp.headers.get('content-length'))
75
- .map(x => parseInt(x))
76
- .getOrElseValue(0) > 0 ? await postprocessed.json() : null;
77
- return json as <%- method.response.responseType %>;
78
- } else {
79
- throw resp;
80
- }
73
+ return requestImpl<<%- method.response.responseType %>>(request, requestOptions);
81
74
  }
@@ -6,7 +6,7 @@ export class ApiClient {
6
6
 
7
7
  <% methods.foreach(method => { %>
8
8
  async <%= method.endpointName %>(
9
- <%_ if (method.parameters.size <= 2) { -%>
9
+ <%_ if (!method.wrapParamsInObject) { -%>
10
10
  <%_ method.parameters.foreach(p => { -%>
11
11
  <%= p.uniqueName %>: <%- p.required && !p.nullable ? p.jsType : `Option<${p.jsType}> = none` %>,
12
12
  <%_ }) -%>
@@ -18,13 +18,13 @@ export class ApiClient {
18
18
  },
19
19
  <%_ } -%>
20
20
  <%_ method.body.foreach(body => { -%>
21
- body: <%= body.type %>,
21
+ body: <%- body.jsType %>,
22
22
  <%_ }); -%>
23
23
  requestOptions: RequestOptions = this.requestOptions
24
24
  ): Promise<TryLike<<%- method.response.asProperty.scatsWrapperType %>>> {
25
25
  return (await Try.promise(() =>
26
26
  <%= method.endpointName %>(
27
- <%_ if (method.parameters.size <= 2) { -%>
27
+ <%_ if (!method.wrapParamsInObject) { -%>
28
28
  <%_ method.parameters.foreach(p => { -%>
29
29
  <%= p.uniqueName %><%- p.required && !p.nullable ? '' : `.orUndefined` %>,
30
30
  <%_ }) -%>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@penkov/swagger-code-gen",
3
- "version": "1.3.2",
3
+ "version": "1.4.0",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "generate-client": "./dist/cli.mjs"
@@ -22,6 +22,7 @@
22
22
  },
23
23
  "homepage": "https://github.com/papirosko/swagger-code-gen#readme",
24
24
  "scripts": {
25
+ "test:petstore": "mkdir -p tmp && ts-node-esm ./src/cli.mjs --enableScats --url https://petstore3.swagger.io/api/v3/openapi.json tmp/petstore.ts",
25
26
  "clean": "rimraf dist",
26
27
  "lint": "eslint \"{src,test}/**/*.ts\" --fix",
27
28
  "prebuild": "npm run lint && npm run clean",