swagger-typescript-api 12.0.2 → 12.0.3

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/LICENSE CHANGED
@@ -1,22 +1,22 @@
1
- MIT License
2
-
3
- Copyright (c) 2019-present acacode
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining
6
- a copy of this software and associated documentation files (the
7
- 'Software'), to deal in the Software without restriction, including
8
- without limitation the rights to use, copy, modify, merge, publish,
9
- distribute, sublicense, and/or sell copies of the Software, and to
10
- permit persons to whom the Software is furnished to do so, subject to
11
- the following conditions:
12
-
13
- The above copyright notice and this permission notice shall be
14
- included in all copies or substantial portions of the Software.
15
-
16
- THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
17
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20
- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21
- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
1
+ MIT License
2
+
3
+ Copyright (c) 2019-present acacode
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ 'Software'), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22
22
  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  [![NPM badge](https://img.shields.io/npm/v/swagger-typescript-api.svg)](https://www.npmjs.com/package/swagger-typescript-api)
4
4
  [![CI](https://github.com/acacode/swagger-typescript-api/actions/workflows/main.yml/badge.svg?branch=next)](https://github.com/acacode/swagger-typescript-api/actions/workflows/main.yml) <!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
5
- [![All Contributors](https://img.shields.io/badge/all_contributors-32-orange.svg)](#contributors)
5
+ [![All Contributors](https://img.shields.io/badge/all_contributors-33-orange.svg)](#contributors)
6
6
  <!-- ALL-CONTRIBUTORS-BADGE:END -->
7
7
 
8
8
  <img src="https://raw.githubusercontent.com/acacode/swagger-typescript-api/master/assets/swagger-typescript-api-logo.png" align="left"
@@ -21,9 +21,15 @@ Any questions you can ask [**here**](https://github.com/acacode/swagger-typescri
21
21
 
22
22
  ![](https://raw.githubusercontent.com/acacode/swagger-typescript-api/master/assets/components-converter-example.jpg)
23
23
 
24
- 👀 This project is looking for a code maintainer 👀
25
24
  P.S. If you are creating the PR, please check your changes with using command `npm run prepare`
26
- P.S. If you want to contribute please use branch `next`. All PRs which will have target `master` will be declined
25
+ P.S. If you want to contribute please use the `next` branch. All PRs that has target `master` will be declined!
26
+
27
+
28
+ Thanks to [Jetbrains](https://www.jetbrains.com/?from=swaggertypescriptapi) for providing a free license for their excellent Webstorm IDE.
29
+ <a href="https://www.jetbrains.com/?from=swaggertypescriptapi">
30
+ <img src="https://upload.wikimedia.org/wikipedia/commons/1/1a/JetBrains_Logo_2016.svg" alt="Jetbrains">
31
+ </a>
32
+
27
33
 
28
34
  ## 👀 Examples
29
35
 
@@ -529,6 +535,8 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
529
535
  <td align="center"><a href="https://github.com/ApacheEx"><img src="https://avatars.githubusercontent.com/u/1918108?v=4?s=100" width="100px;" alt="Oleg Kuzava"/><br /><sub><b>Oleg Kuzava</b></sub></a><br /><a href="https://github.com/acacode/swagger-typescript-api/commits?author=ApacheEx" title="Code">💻</a> <a href="https://github.com/acacode/swagger-typescript-api/issues?q=author%3AApacheEx" title="Bug reports">🐛</a></td>
530
536
  <td align="center"><a href="http://nikz.se"><img src="https://avatars.githubusercontent.com/u/7352072?v=4?s=100" width="100px;" alt="Niklas Frank"/><br /><sub><b>Niklas Frank</b></sub></a><br /><a href="https://github.com/acacode/swagger-typescript-api/commits?author=nksfrank" title="Code">💻</a> <a href="https://github.com/acacode/swagger-typescript-api/issues?q=author%3Anksfrank" title="Bug reports">🐛</a></td>
531
537
  <td align="center"><a href="https://quentinbrunet.com"><img src="https://avatars.githubusercontent.com/u/20137632?v=4?s=100" width="100px;" alt="Quentin Brunet"/><br /><sub><b>Quentin Brunet</b></sub></a><br /><a href="https://github.com/acacode/swagger-typescript-api/commits?author=qboot" title="Code">💻</a></td>
538
+ <td align="center"><a href="https://github.com/Soarc"><img src="https://avatars.githubusercontent.com/u/3385495?v=4?s=100" width="100px;" alt="Gor Rustamyan"/><br /><sub><b>Gor Rustamyan</b></sub></a><br /><a href="https://github.com/acacode/swagger-typescript-api/commits?author=Soarc" title="Code">💻</a> <a href="https://github.com/acacode/swagger-typescript-api/issues?q=author%3ASoarc" title="Bug reports">🐛</a></td>
539
+ <td align="center"><a href="https://github.com/JochenDiekenbrock"><img src="https://avatars.githubusercontent.com/u/1625222?v=4?s=100" width="100px;" alt="Jochen Diekenbrock"/><br /><sub><b>Jochen Diekenbrock</b></sub></a><br /><a href="https://github.com/acacode/swagger-typescript-api/commits?author=JochenDiekenbrock" title="Code">💻</a> <a href="https://github.com/acacode/swagger-typescript-api/issues?q=author%3AJochenDiekenbrock" title="Bug reports">🐛</a></td>
532
540
  </tr>
533
541
  </tbody>
534
542
  </table>
package/index.d.ts CHANGED
@@ -144,20 +144,28 @@ interface GenerateApiParamsBase {
144
144
 
145
145
  /** extract all enums from nested types\interfaces to `enum` construction */
146
146
  extractEnums?: boolean;
147
+
147
148
  /** prefix string value needed to fix invalid type names (default: 'Type') */
148
149
  fixInvalidTypeNamePrefix?: string;
150
+
149
151
  /** prefix string value needed to fix invalid enum keys (default: 'Value') */
150
152
  fixInvalidEnumKeyPrefix?: string;
153
+
151
154
  /** prefix string value for enum keys */
152
155
  enumKeyPrefix?: string;
156
+
153
157
  /** suffix string value for enum keys */
154
158
  enumKeySuffix?: string;
159
+
155
160
  /** prefix string value for type names */
156
161
  typePrefix?: string;
162
+
157
163
  /** suffix string value for type names */
158
164
  typeSuffix?: string;
165
+
159
166
  /** extra configuration for extracting type names operations */
160
167
  extractingOptions?: Partial<ExtractingOptions>;
168
+
161
169
  /** configuration for fetching swagger schema requests */
162
170
  requestOptions?: null | Partial<import("node-fetch").RequestInit>;
163
171
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "swagger-typescript-api",
3
- "version": "12.0.2",
3
+ "version": "12.0.3",
4
4
  "description": "Generate typescript/javascript api from swagger schema",
5
5
  "scripts": {
6
6
  "cli:json": "node index.js -r -d -p ./swagger-test-cli.json -n swagger-test-cli.ts",
@@ -14,6 +14,7 @@
14
14
  "test-all-extended": "node --unhandled-rejections=strict ./scriptsRunner.js generate-extended validate generate validate test:*",
15
15
  "test-specific": "node ./scriptsRunner.js generate validate test:*",
16
16
  "test-specific-only": "node ./scriptsRunner.js test:*",
17
+ "prepare": "npm run test-all-extended",
17
18
  "generate": "node tests/generate.js",
18
19
  "generate-extended": "node tests/generate-extended.js",
19
20
  "generate:debug": "node --nolazy tests/generate.js",
@@ -80,7 +81,7 @@
80
81
  "@types/swagger-schema-official": "2.0.22",
81
82
  "cosmiconfig": "7.0.1",
82
83
  "didyoumean": "^1.2.2",
83
- "eta": "1.12.3",
84
+ "eta": "^2.0.0",
84
85
  "js-yaml": "4.1.0",
85
86
  "lodash": "4.17.21",
86
87
  "make-dir": "3.1.0",
@@ -1,17 +1,17 @@
1
- # swagger-typescript-api
2
-
3
- # templates
4
-
5
- Templates:
6
- - `api.ejs` - *(generates file)* Api class module (locations: [default](https://github.com/acacode/swagger-typescript-api/tree/next/templates/default/api.ejs), [modular](https://github.com/acacode/swagger-typescript-api/tree/next/templates/modular/api.ejs))
7
- - `data-contracts.ejs` - *(generates file)* all types (data contracts) from swagger schema (locations: [base](https://github.com/acacode/swagger-typescript-api/tree/next/templates/base/data-contracts.ejs))
8
- - `http-client.ejs` - *(generates file)* HttpClient class module (locations: [base](https://github.com/acacode/swagger-typescript-api/tree/next/templates/base/http-client.ejs))
9
- - `procedure-call.ejs` - *(subtemplate)* route in Api class (locations: [default](https://github.com/acacode/swagger-typescript-api/tree/next/templates/default/procedure-call.ejs), [modular](https://github.com/acacode/swagger-typescript-api/tree/next/templates/modular/procedure-call.ejs))
10
- - `route-docs.ejs` - *(generates file)* documentation for route in Api class (locations: [base](https://github.com/acacode/swagger-typescript-api/tree/next/templates/base/route-docs.ejs))
11
- - `route-name.ejs` - *(subtemplate)* route name for route in Api class (locations: [base](https://github.com/acacode/swagger-typescript-api/tree/next/templates/base/route-name.ejs))
12
- - `route-type.ejs` - *(`--route-types` option)* *(subtemplate)* (locations: [base](https://github.com/acacode/swagger-typescript-api/tree/next/templates/base/route-type.ejs))
13
- - `route-types.ejs` - *(`--route-types` option)* *(subtemplate)* (locations: [base](https://github.com/acacode/swagger-typescript-api/tree/next/templates/base/route-types.ejs)) - `data-contract-jsdoc.ejs` - *(subtemplate)* generates JSDOC for data contract (locations: [base](https://github.com/acacode/swagger-typescript-api/tree/next/templates/base/data-contract-jsdoc.ejs))
14
-
15
- [//]: # (- `enum-data-contract.ejs` - *&#40;subtemplate&#41;* generates `enum` data contract &#40;locations: [base]&#40;https://github.com/acacode/swagger-typescript-api/tree/next/templates/base/enum-data-contract.ejs&#41;&#41;)
16
- [//]: # (- `interface-data-contract.ejs` - *&#40;subtemplate&#41;* generates `interface` data contract &#40;locations: [base]&#40;https://github.com/acacode/swagger-typescript-api/tree/next/templates/base/interface-data-contract.ejs&#41;&#41;)
17
- [//]: # (- `type-data-contract.ejs` - *&#40;subtemplate&#41;* generates `type` data contract &#40;locations: [base]&#40;https://github.com/acacode/swagger-typescript-api/tree/next/templates/base/type-data-contract.ejs&#41;&#41;)
1
+ # swagger-typescript-api
2
+
3
+ # templates
4
+
5
+ Templates:
6
+ - `api.ejs` - *(generates file)* Api class module (locations: [default](https://github.com/acacode/swagger-typescript-api/tree/next/templates/default/api.ejs), [modular](https://github.com/acacode/swagger-typescript-api/tree/next/templates/modular/api.ejs))
7
+ - `data-contracts.ejs` - *(generates file)* all types (data contracts) from swagger schema (locations: [base](https://github.com/acacode/swagger-typescript-api/tree/next/templates/base/data-contracts.ejs))
8
+ - `http-client.ejs` - *(generates file)* HttpClient class module (locations: [base](https://github.com/acacode/swagger-typescript-api/tree/next/templates/base/http-client.ejs))
9
+ - `procedure-call.ejs` - *(subtemplate)* route in Api class (locations: [default](https://github.com/acacode/swagger-typescript-api/tree/next/templates/default/procedure-call.ejs), [modular](https://github.com/acacode/swagger-typescript-api/tree/next/templates/modular/procedure-call.ejs))
10
+ - `route-docs.ejs` - *(generates file)* documentation for route in Api class (locations: [base](https://github.com/acacode/swagger-typescript-api/tree/next/templates/base/route-docs.ejs))
11
+ - `route-name.ejs` - *(subtemplate)* route name for route in Api class (locations: [base](https://github.com/acacode/swagger-typescript-api/tree/next/templates/base/route-name.ejs))
12
+ - `route-type.ejs` - *(`--route-types` option)* *(subtemplate)* (locations: [base](https://github.com/acacode/swagger-typescript-api/tree/next/templates/base/route-type.ejs))
13
+ - `route-types.ejs` - *(`--route-types` option)* *(subtemplate)* (locations: [base](https://github.com/acacode/swagger-typescript-api/tree/next/templates/base/route-types.ejs)) - `data-contract-jsdoc.ejs` - *(subtemplate)* generates JSDOC for data contract (locations: [base](https://github.com/acacode/swagger-typescript-api/tree/next/templates/base/data-contract-jsdoc.ejs))
14
+
15
+ [//]: # (- `enum-data-contract.ejs` - *&#40;subtemplate&#41;* generates `enum` data contract &#40;locations: [base]&#40;https://github.com/acacode/swagger-typescript-api/tree/next/templates/base/enum-data-contract.ejs&#41;&#41;)
16
+ [//]: # (- `interface-data-contract.ejs` - *&#40;subtemplate&#41;* generates `interface` data contract &#40;locations: [base]&#40;https://github.com/acacode/swagger-typescript-api/tree/next/templates/base/interface-data-contract.ejs&#41;&#41;)
17
+ [//]: # (- `type-data-contract.ejs` - *&#40;subtemplate&#41;* generates `type` data contract &#40;locations: [base]&#40;https://github.com/acacode/swagger-typescript-api/tree/next/templates/base/type-data-contract.ejs&#41;&#41;)
@@ -1,8 +1,8 @@
1
- # swagger-typescript-api
2
-
3
- # templates/base
4
-
5
- This templates use both for multiple api files and single api file
6
-
7
-
1
+ # swagger-typescript-api
2
+
3
+ # templates/base
4
+
5
+ This templates use both for multiple api files and single api file
6
+
7
+
8
8
  path prefix `@base`
@@ -1,37 +1,37 @@
1
- <%
2
- const { data, utils } = it;
3
- const { formatDescription, require, _ } = utils;
4
-
5
- const stringify = (value) => _.isObject(value) ? JSON.stringify(value) : _.isString(value) ? `"${value}"` : value
6
-
7
- const jsDocLines = _.compact([
8
- data.title,
9
- data.description && formatDescription(data.description),
10
- !_.isUndefined(data.deprecated) && data.deprecated && '@deprecated',
11
- !_.isUndefined(data.format) && `@format ${data.format}`,
12
- !_.isUndefined(data.minimum) && `@min ${data.minimum}`,
13
- !_.isUndefined(data.multipleOf) && `@multipleOf ${data.multipleOf}`,
14
- !_.isUndefined(data.exclusiveMinimum) && `@exclusiveMin ${data.exclusiveMinimum}`,
15
- !_.isUndefined(data.maximum) && `@max ${data.maximum}`,
16
- !_.isUndefined(data.minLength) && `@minLength ${data.minLength}`,
17
- !_.isUndefined(data.maxLength) && `@maxLength ${data.maxLength}`,
18
- !_.isUndefined(data.exclusiveMaximum) && `@exclusiveMax ${data.exclusiveMaximum}`,
19
- !_.isUndefined(data.maxItems) && `@maxItems ${data.maxItems}`,
20
- !_.isUndefined(data.minItems) && `@minItems ${data.minItems}`,
21
- !_.isUndefined(data.uniqueItems) && `@uniqueItems ${data.uniqueItems}`,
22
- !_.isUndefined(data.default) && `@default ${stringify(data.default)}`,
23
- !_.isUndefined(data.pattern) && `@pattern ${data.pattern}`,
24
- !_.isUndefined(data.example) && `@example ${stringify(data.example)}`
25
- ]).join('\n').split('\n');
26
- %>
27
- <% if (jsDocLines.every(_.isEmpty)) { %>
28
- <% } else if (jsDocLines.length === 1) { %>
29
- /** <%~ jsDocLines[0] %> */
30
- <% } else if (jsDocLines.length) { %>
31
- /**
32
- <% for (jsDocLine of jsDocLines) { %>
33
- * <%~ jsDocLine %>
34
-
35
- <% } %>
36
- */
37
- <% } %>
1
+ <%
2
+ const { data, utils } = it;
3
+ const { formatDescription, require, _ } = utils;
4
+
5
+ const stringify = (value) => _.isObject(value) ? JSON.stringify(value) : _.isString(value) ? `"${value}"` : value
6
+
7
+ const jsDocLines = _.compact([
8
+ data.title,
9
+ data.description && formatDescription(data.description),
10
+ !_.isUndefined(data.deprecated) && data.deprecated && '@deprecated',
11
+ !_.isUndefined(data.format) && `@format ${data.format}`,
12
+ !_.isUndefined(data.minimum) && `@min ${data.minimum}`,
13
+ !_.isUndefined(data.multipleOf) && `@multipleOf ${data.multipleOf}`,
14
+ !_.isUndefined(data.exclusiveMinimum) && `@exclusiveMin ${data.exclusiveMinimum}`,
15
+ !_.isUndefined(data.maximum) && `@max ${data.maximum}`,
16
+ !_.isUndefined(data.minLength) && `@minLength ${data.minLength}`,
17
+ !_.isUndefined(data.maxLength) && `@maxLength ${data.maxLength}`,
18
+ !_.isUndefined(data.exclusiveMaximum) && `@exclusiveMax ${data.exclusiveMaximum}`,
19
+ !_.isUndefined(data.maxItems) && `@maxItems ${data.maxItems}`,
20
+ !_.isUndefined(data.minItems) && `@minItems ${data.minItems}`,
21
+ !_.isUndefined(data.uniqueItems) && `@uniqueItems ${data.uniqueItems}`,
22
+ !_.isUndefined(data.default) && `@default ${stringify(data.default)}`,
23
+ !_.isUndefined(data.pattern) && `@pattern ${data.pattern}`,
24
+ !_.isUndefined(data.example) && `@example ${stringify(data.example)}`
25
+ ]).join('\n').split('\n');
26
+ %>
27
+ <% if (jsDocLines.every(_.isEmpty)) { %>
28
+ <% } else if (jsDocLines.length === 1) { %>
29
+ /** <%~ jsDocLines[0] %> */
30
+ <% } else if (jsDocLines.length) { %>
31
+ /**
32
+ <% for (jsDocLine of jsDocLines) { %>
33
+ * <%~ jsDocLine %>
34
+
35
+ <% } %>
36
+ */
37
+ <% } %>
@@ -1,28 +1,28 @@
1
- <%
2
- const { modelTypes, utils, config } = it;
3
- const { formatDescription, require, _, Ts } = utils;
4
-
5
-
6
- const dataContractTemplates = {
7
- enum: (contract) => {
8
- return `enum ${contract.name} {\r\n${contract.content} \r\n }`;
9
- },
10
- interface: (contract) => {
11
- return `interface ${contract.name} {\r\n${contract.content}}`;
12
- },
13
- type: (contract) => {
14
- return `type ${contract.name} = ${contract.content}`;
15
- },
16
- }
17
- %>
18
-
19
- <% if (config.internalTemplateOptions.addUtilRequiredKeysType) { %>
20
- type <%~ config.Ts.CodeGenKeyword.UtilRequiredKeys %><T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>
21
- <% } %>
22
-
23
- <% modelTypes.forEach((contract) => { %>
24
- <%~ includeFile('@base/data-contract-jsdoc.ejs', { ...it, data: { ...contract, ...contract.typeData } }) %>
25
- export <%~ (dataContractTemplates[contract.typeIdentifier] || dataContractTemplates.type)(contract) %>
26
-
27
-
28
- <% }) %>
1
+ <%
2
+ const { modelTypes, utils, config } = it;
3
+ const { formatDescription, require, _, Ts } = utils;
4
+
5
+
6
+ const dataContractTemplates = {
7
+ enum: (contract) => {
8
+ return `enum ${contract.name} {\r\n${contract.content} \r\n }`;
9
+ },
10
+ interface: (contract) => {
11
+ return `interface ${contract.name} {\r\n${contract.content}}`;
12
+ },
13
+ type: (contract) => {
14
+ return `type ${contract.name} = ${contract.content}`;
15
+ },
16
+ }
17
+ %>
18
+
19
+ <% if (config.internalTemplateOptions.addUtilRequiredKeysType) { %>
20
+ type <%~ config.Ts.CodeGenKeyword.UtilRequiredKeys %><T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>
21
+ <% } %>
22
+
23
+ <% modelTypes.forEach((contract) => { %>
24
+ <%~ includeFile('@base/data-contract-jsdoc.ejs', { ...it, data: { ...contract, ...contract.typeData } }) %>
25
+ export <%~ (dataContractTemplates[contract.typeIdentifier] || dataContractTemplates.type)(contract) %>
26
+
27
+
28
+ <% }) %>
@@ -1,12 +1,12 @@
1
- <%
2
- const { contract, utils, config } = it;
3
- const { formatDescription, require, _ } = utils;
4
- const { name, $content } = contract;
5
- %>
6
- <% if (config.generateUnionEnums) { %>
7
- export type <%~ name %> = <%~ _.map($content, ({ value }) => value).join(" | ") %>
8
- <% } else { %>
9
- export enum <%~ name %> {
10
- <%~ _.map($content, ({ key, value }) => `${key} = ${value}`).join(",\n") %>
11
- }
12
- <% } %>
1
+ <%
2
+ const { contract, utils, config } = it;
3
+ const { formatDescription, require, _ } = utils;
4
+ const { name, $content } = contract;
5
+ %>
6
+ <% if (config.generateUnionEnums) { %>
7
+ export type <%~ name %> = <%~ _.map($content, ({ value }) => value).join(" | ") %>
8
+ <% } else { %>
9
+ export enum <%~ name %> {
10
+ <%~ _.map($content, ({ key, value }) => `${key} = ${value}`).join(",\n") %>
11
+ }
12
+ <% } %>
@@ -1,3 +1,3 @@
1
- <% const { config } = it; %>
2
- <% /* https://github.com/acacode/swagger-typescript-api/tree/next/templates/base/http-clients/ */ %>
1
+ <% const { config } = it; %>
2
+ <% /* https://github.com/acacode/swagger-typescript-api/tree/next/templates/base/http-clients/ */ %>
3
3
  <%~ includeFile(`@base/http-clients/${config.httpClientType}-http-client`, it) %>
@@ -1,138 +1,138 @@
1
- <%
2
- const { apiConfig, generateResponses, config } = it;
3
- %>
4
-
5
- import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, ResponseType, HeadersDefaults } from "axios";
6
-
7
- export type QueryParamsType = Record<string | number, any>;
8
-
9
- export interface FullRequestParams extends Omit<AxiosRequestConfig, "data" | "params" | "url" | "responseType"> {
10
- /** set parameter to `true` for call `securityWorker` for this request */
11
- secure?: boolean;
12
- /** request path */
13
- path: string;
14
- /** content type of request body */
15
- type?: ContentType;
16
- /** query params */
17
- query?: QueryParamsType;
18
- /** format of response (i.e. response.json() -> format: "json") */
19
- format?: ResponseType;
20
- /** request body */
21
- body?: unknown;
22
- }
23
-
24
- export type RequestParams = Omit<FullRequestParams, "body" | "method" | "query" | "path">;
25
-
26
- export interface ApiConfig<SecurityDataType = unknown> extends Omit<AxiosRequestConfig, "data" | "cancelToken"> {
27
- securityWorker?: (securityData: SecurityDataType | null) => Promise<AxiosRequestConfig | void> | AxiosRequestConfig | void;
28
- secure?: boolean;
29
- format?: ResponseType;
30
- }
31
-
32
- export enum ContentType {
33
- Json = "application/json",
34
- FormData = "multipart/form-data",
35
- UrlEncoded = "application/x-www-form-urlencoded",
36
- Text = "text/plain",
37
- }
38
-
39
- export class HttpClient<SecurityDataType = unknown> {
40
- public instance: AxiosInstance;
41
- private securityData: SecurityDataType | null = null;
42
- private securityWorker?: ApiConfig<SecurityDataType>["securityWorker"];
43
- private secure?: boolean;
44
- private format?: ResponseType;
45
-
46
- constructor({ securityWorker, secure, format, ...axiosConfig }: ApiConfig<SecurityDataType> = {}) {
47
- this.instance = axios.create({ ...axiosConfig, baseURL: axiosConfig.baseURL || "<%~ apiConfig.baseUrl %>" })
48
- this.secure = secure;
49
- this.format = format;
50
- this.securityWorker = securityWorker;
51
- }
52
-
53
- public setSecurityData = (data: SecurityDataType | null) => {
54
- this.securityData = data
55
- }
56
-
57
- protected mergeRequestParams(params1: AxiosRequestConfig, params2?: AxiosRequestConfig): AxiosRequestConfig {
58
- const method = params1.method || (params2 && params2.method)
59
-
60
- return {
61
- ...this.instance.defaults,
62
- ...params1,
63
- ...(params2 || {}),
64
- headers: {
65
- ...((method && this.instance.defaults.headers[method.toLowerCase() as keyof HeadersDefaults]) || {}),
66
- ...(params1.headers || {}),
67
- ...((params2 && params2.headers) || {}),
68
- },
69
- };
70
- }
71
-
72
- protected stringifyFormItem(formItem: unknown) {
73
- if (typeof formItem === "object" && formItem !== null) {
74
- return JSON.stringify(formItem);
75
- } else {
76
- return `${formItem}`;
77
- }
78
- }
79
-
80
- protected createFormData(input: Record<string, unknown>): FormData {
81
- return Object.keys(input || {}).reduce((formData, key) => {
82
- const property = input[key];
83
- const propertyContent: any[] = (property instanceof Array) ? property : [property]
84
-
85
- for (const formItem of propertyContent) {
86
- const isFileType = formItem instanceof Blob || formItem instanceof File;
87
- formData.append(
88
- key,
89
- isFileType ? formItem : this.stringifyFormItem(formItem)
90
- );
91
- }
92
-
93
- return formData;
94
- }, new FormData());
95
- }
96
-
97
- public request = async <T = any, _E = any>({
98
- secure,
99
- path,
100
- type,
101
- query,
102
- format,
103
- body,
104
- ...params
105
- <% if (config.unwrapResponseData) { %>
106
- }: FullRequestParams): Promise<T> => {
107
- <% } else { %>
108
- }: FullRequestParams): Promise<AxiosResponse<T>> => {
109
- <% } %>
110
- const secureParams = ((typeof secure === 'boolean' ? secure : this.secure) && this.securityWorker && (await this.securityWorker(this.securityData))) || {};
111
- const requestParams = this.mergeRequestParams(params, secureParams);
112
- const responseFormat = (format || this.format) || undefined;
113
-
114
- if (type === ContentType.FormData && body && body !== null && typeof body === "object") {
115
- body = this.createFormData(body as Record<string, unknown>);
116
- }
117
-
118
- if (type === ContentType.Text && body && body !== null && typeof body !== "string") {
119
- body = JSON.stringify(body);
120
- }
121
-
122
- return this.instance.request({
123
- ...requestParams,
124
- headers: {
125
- ...(requestParams.headers || {}),
126
- ...(type && type !== ContentType.FormData ? { "Content-Type": type } : {}),
127
- },
128
- params: query,
129
- responseType: responseFormat,
130
- data: body,
131
- url: path,
132
- <% if (config.unwrapResponseData) { %>
133
- }).then(response => response.data);
134
- <% } else { %>
135
- });
136
- <% } %>
137
- };
138
- }
1
+ <%
2
+ const { apiConfig, generateResponses, config } = it;
3
+ %>
4
+
5
+ import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, ResponseType, HeadersDefaults } from "axios";
6
+
7
+ export type QueryParamsType = Record<string | number, any>;
8
+
9
+ export interface FullRequestParams extends Omit<AxiosRequestConfig, "data" | "params" | "url" | "responseType"> {
10
+ /** set parameter to `true` for call `securityWorker` for this request */
11
+ secure?: boolean;
12
+ /** request path */
13
+ path: string;
14
+ /** content type of request body */
15
+ type?: ContentType;
16
+ /** query params */
17
+ query?: QueryParamsType;
18
+ /** format of response (i.e. response.json() -> format: "json") */
19
+ format?: ResponseType;
20
+ /** request body */
21
+ body?: unknown;
22
+ }
23
+
24
+ export type RequestParams = Omit<FullRequestParams, "body" | "method" | "query" | "path">;
25
+
26
+ export interface ApiConfig<SecurityDataType = unknown> extends Omit<AxiosRequestConfig, "data" | "cancelToken"> {
27
+ securityWorker?: (securityData: SecurityDataType | null) => Promise<AxiosRequestConfig | void> | AxiosRequestConfig | void;
28
+ secure?: boolean;
29
+ format?: ResponseType;
30
+ }
31
+
32
+ export enum ContentType {
33
+ Json = "application/json",
34
+ FormData = "multipart/form-data",
35
+ UrlEncoded = "application/x-www-form-urlencoded",
36
+ Text = "text/plain",
37
+ }
38
+
39
+ export class HttpClient<SecurityDataType = unknown> {
40
+ public instance: AxiosInstance;
41
+ private securityData: SecurityDataType | null = null;
42
+ private securityWorker?: ApiConfig<SecurityDataType>["securityWorker"];
43
+ private secure?: boolean;
44
+ private format?: ResponseType;
45
+
46
+ constructor({ securityWorker, secure, format, ...axiosConfig }: ApiConfig<SecurityDataType> = {}) {
47
+ this.instance = axios.create({ ...axiosConfig, baseURL: axiosConfig.baseURL || "<%~ apiConfig.baseUrl %>" })
48
+ this.secure = secure;
49
+ this.format = format;
50
+ this.securityWorker = securityWorker;
51
+ }
52
+
53
+ public setSecurityData = (data: SecurityDataType | null) => {
54
+ this.securityData = data
55
+ }
56
+
57
+ protected mergeRequestParams(params1: AxiosRequestConfig, params2?: AxiosRequestConfig): AxiosRequestConfig {
58
+ const method = params1.method || (params2 && params2.method)
59
+
60
+ return {
61
+ ...this.instance.defaults,
62
+ ...params1,
63
+ ...(params2 || {}),
64
+ headers: {
65
+ ...((method && this.instance.defaults.headers[method.toLowerCase() as keyof HeadersDefaults]) || {}),
66
+ ...(params1.headers || {}),
67
+ ...((params2 && params2.headers) || {}),
68
+ },
69
+ };
70
+ }
71
+
72
+ protected stringifyFormItem(formItem: unknown) {
73
+ if (typeof formItem === "object" && formItem !== null) {
74
+ return JSON.stringify(formItem);
75
+ } else {
76
+ return `${formItem}`;
77
+ }
78
+ }
79
+
80
+ protected createFormData(input: Record<string, unknown>): FormData {
81
+ return Object.keys(input || {}).reduce((formData, key) => {
82
+ const property = input[key];
83
+ const propertyContent: any[] = (property instanceof Array) ? property : [property]
84
+
85
+ for (const formItem of propertyContent) {
86
+ const isFileType = formItem instanceof Blob || formItem instanceof File;
87
+ formData.append(
88
+ key,
89
+ isFileType ? formItem : this.stringifyFormItem(formItem)
90
+ );
91
+ }
92
+
93
+ return formData;
94
+ }, new FormData());
95
+ }
96
+
97
+ public request = async <T = any, _E = any>({
98
+ secure,
99
+ path,
100
+ type,
101
+ query,
102
+ format,
103
+ body,
104
+ ...params
105
+ <% if (config.unwrapResponseData) { %>
106
+ }: FullRequestParams): Promise<T> => {
107
+ <% } else { %>
108
+ }: FullRequestParams): Promise<AxiosResponse<T>> => {
109
+ <% } %>
110
+ const secureParams = ((typeof secure === 'boolean' ? secure : this.secure) && this.securityWorker && (await this.securityWorker(this.securityData))) || {};
111
+ const requestParams = this.mergeRequestParams(params, secureParams);
112
+ const responseFormat = (format || this.format) || undefined;
113
+
114
+ if (type === ContentType.FormData && body && body !== null && typeof body === "object") {
115
+ body = this.createFormData(body as Record<string, unknown>);
116
+ }
117
+
118
+ if (type === ContentType.Text && body && body !== null && typeof body !== "string") {
119
+ body = JSON.stringify(body);
120
+ }
121
+
122
+ return this.instance.request({
123
+ ...requestParams,
124
+ headers: {
125
+ ...(requestParams.headers || {}),
126
+ ...(type && type !== ContentType.FormData ? { "Content-Type": type } : {}),
127
+ },
128
+ params: query,
129
+ responseType: responseFormat,
130
+ data: body,
131
+ url: path,
132
+ <% if (config.unwrapResponseData) { %>
133
+ }).then(response => response.data);
134
+ <% } else { %>
135
+ });
136
+ <% } %>
137
+ };
138
+ }