codegen-openapi-ts 0.3.1 → 0.3.5

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
@@ -2,6 +2,7 @@
2
2
 
3
3
  [![NPM][npm-image]][npm-url]
4
4
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
+ ![Build](https://github.com/devTeaa/codegen-openapi-ts/actions/workflows/CI.yml/badge.svg)
5
6
 
6
7
  > Node.js library that generates Typescript clients based on the OpenAPI specification.
7
8
 
@@ -11,11 +12,12 @@
11
12
  - Frontend ❤️ OpenAPI, but we do not want to use JAVA codegen in our builds
12
13
  - Quick, lightweight, robust and framework-agnostic 🚀
13
14
  - Supports generation of TypeScript clients
14
- - Supports conversion from Swagger 1.x/2.x to OpenAPI 2.x/3.x
15
+ - Supports conversion from Swagger 1.x/2.x to OpenAPI 2.x/3.x with [`api-spec-converter`](https://github.com/LucyBot-Inc/api-spec-converter)
15
16
  - Supports JSON and YAML files for input
16
- - Supports generation through CLI, Node.js and NPX
17
+ - Supports generation through Node.js
17
18
  - Supports tsc and @babel/plugin-transform-typescript
18
19
  - Supports external references using [`json-schema-ref-parser`](https://github.com/APIDevTools/json-schema-ref-parser/)
20
+ - Supports generate multiple api based on config file
19
21
 
20
22
  ## Install
21
23
 
@@ -26,162 +28,110 @@ npm install codegen-openapi-ts --save-dev
26
28
 
27
29
  ## Usage
28
30
 
31
+ **codegen.config.js**
29
32
  ```
30
- $ openapi --help
31
-
32
- Usage: openapi [options]
33
-
34
- Options:
35
- -V, --version output the version number
36
- -i, --input <value> OpenAPI specification, can be a path, url or string content (required)
37
- -o, --output <value> Output directory (required)
38
- --useUnionTypes Use union types instead of enums
39
- --exportServices <value> Write services to disk (default: true)
40
- --exportModels <value> Write models to disk (default: true)
41
- --postfix <value> Service name postfix (default: "Service")
42
- --request <value> Path to custom request file
43
- -h, --help display help for command
44
-
45
- Examples
46
- $ openapi --input ./spec.json
47
- $ openapi --input ./spec.json --output ./dist
48
- $ openapi --input ./spec.json --output ./dist --client xhr
33
+ codegen-openapi-ts --help
34
+ Usage: codegen-openapi-ts [options]
35
+
36
+ Options:
37
+ -V, --version output the version number
38
+ --config <value> Path to config file (default: "codegen.config.js")
39
+ -h, --help display help for command
49
40
  ```
50
41
 
42
+ **CLI**
43
+ ```
44
+ codegen-openapi-ts-cli --help
45
+ Usage: codegen-openapi-ts-cli [options]
51
46
 
52
- ## Example
47
+ Arguments:
48
+ from Original response specification version
49
+ source Swagger/OpenAPI response url
50
+ output Output folder name (default: "output")
53
51
 
54
- **package.json**
55
- ```json
56
- {
57
- "scripts": {
58
- "generate": "openapi --input ./spec.json --output ./dist"
59
- }
60
- }
52
+ Options:
53
+ -V, --version output the version number
54
+ -h, --help display help for command
61
55
  ```
62
56
 
63
- **NPX**
64
-
57
+ **Node**
65
58
  ```
66
- npx codegen-openapi-ts --input ./spec.json --output ./dist
59
+ OpenAPI.convertAndGenerate({
60
+ from: string, // swagger_1, swagger_2, openapi_3, api_blueprint, io_docs, google, raml, wadl
61
+ to: string, // swagger_1, swagger_2, openapi_3, api_blueprint, io_docs, google, raml, wadl
62
+ source: string // url or local file (JSON, YAML)
63
+ }, {
64
+ input: string, // generated conversion output path, also used as input
65
+ output: string, // generated output folder location
66
+ useOptions: boolean, // use options as url methods argument
67
+ useUnionTypes: boolean // use union types instead of enum
68
+ })
67
69
  ```
68
70
 
69
- **Node.js API**
70
71
 
72
+ ## Example
73
+ **codegen.config.js**
71
74
  ```javascript
72
- const OpenAPI = require('codegen-openapi-ts');
73
-
74
- OpenAPI.generate({
75
- input: './spec.json',
76
- output: './dist'
77
- });
78
-
79
- // Or by providing the content of the spec directly 🚀
80
- OpenAPI.generate({
81
- input: require('./spec.json'),
82
- output: './dist'
83
- });
75
+ 'use strict';
76
+
77
+ module.exports = [
78
+ {
79
+ source: 'http://pokemon-api/docs/api',
80
+ from: 'openapi_3',
81
+ output: 'src/api-types/pokemon-api', // pokemon-api
82
+ },
83
+ ];
84
84
  ```
85
85
 
86
-
87
- ## Features
88
-
89
- ### Enums vs. Union Types `--useUnionTypes`
90
- The OpenAPI spec allows you to define [enums](https://swagger.io/docs/specification/data-models/enums/) inside the
91
- data model. By default, we convert these enums definitions to [TypeScript enums](https://www.typescriptlang.org/docs/handbook/enums.html).
92
- However, these enums are merged inside the namespace of the model, this is unsupported by Babel, [see docs](https://babeljs.io/docs/en/babel-plugin-transform-typescript#impartial-namespace-support).
93
- Because we also want to support projects that use Babel [@babel/plugin-transform-typescript](https://babeljs.io/docs/en/babel-plugin-transform-typescript),
94
- we offer the flag `--useUnionTypes` to generate [union types](https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#union-types)
95
- instead of the traditional enums. The difference can be seen below:
96
-
97
- **Enums:**
98
- ```typescript
99
- // Model
100
- export interface Order {
101
- id?: number;
102
- quantity?: number;
103
- status?: Order.status;
104
- }
105
-
106
- export namespace Order {
107
- export enum status {
108
- PLACED = 'placed',
109
- APPROVED = 'approved',
110
- DELIVERED = 'delivered',
111
- }
112
- }
113
-
114
- // Usage
115
- const order: Order = {
116
- id: 1,
117
- quantity: 40,
118
- status: Order.status.PLACED
119
- }
86
+ **CLI**
87
+ ```bash
88
+ codegen-openapi-ts-cli swagger_2 https://pokemonapi/docs/api
89
+ codegen-openapi-ts-cli swagger_2 https://pokemonapi/docs/api pokemon-api
120
90
  ```
121
91
 
122
- **Union Types:**
123
- ```typescript
124
- // Model
125
- export interface Order {
126
- id?: number;
127
- quantity?: number;
128
- status?: 'placed' | 'approved' | 'delivered';
129
- }
130
-
131
- // Usage
132
- const order: Order = {
133
- id: 1,
134
- quantity: 40,
135
- status: 'placed'
136
- }
92
+ **fetch-schema.js (Node)**
93
+ ```javascript
94
+ // fetch-schema.js
95
+ const OpenAPI = require('codegen-openapi-ts')
96
+
97
+ OpenAPI.convertAndGenerate(
98
+ {
99
+ from: process.argv[2], // swagger_2
100
+ to: 'openapi_3',
101
+ source: process.argv[3] // https://pokemon-api/docs/api
102
+ },
103
+ {
104
+ input: 'scripts/api-schema.json',
105
+ output: 'src/api-types/' + process.argv[4], // pokemon-api
106
+ useOptions: true,
107
+ useUnionTypes: true
108
+ }
109
+ )
137
110
  ```
138
-
139
- ### Enum with custom names and descriptions
140
- You can use `x-enum-varnames` and `x-enum-descriptions` in your spec to generate enum with custom names and descriptions.
141
- It's not in official [spec](https://github.com/OAI/OpenAPI-Specification/issues/681) yet. But it's a supported extension
142
- that can help developers use more meaningful enumerators.
143
111
  ```json
112
+ // package.json
144
113
  {
145
- "EnumWithStrings": {
146
- "description": "This is a simple enum with strings",
147
- "enum": [
148
- 0,
149
- 1,
150
- 2
151
- ],
152
- "x-enum-varnames": [
153
- "Success",
154
- "Warning",
155
- "Error"
156
- ],
157
- "x-enum-descriptions": [
158
- "Used when the status of something is successful",
159
- "Used when the status of something has a warning",
160
- "Used when the status of something has an error"
161
- ]
114
+ "scripts": {
115
+ "generate": "node fetch-schema.js swagger_2 https://pokemon-api/docs/api pokemon-api"
162
116
  }
163
117
  }
164
- ```
165
118
 
166
- Generated code:
167
- ```typescript
168
- enum EnumWithStrings {
169
- /*
170
- * Used when the status of something is successful
171
- */
172
- Success = 0,
173
- /*
174
- * Used when the status of something has a warning
175
- */
176
- Waring = 1,
177
- /*
178
- * Used when the status of something has an error
179
- */
180
- Error = 2,
181
- }
119
+ // npm run generate
182
120
  ```
121
+ ### Output folder
122
+ .
123
+ ├── ...
124
+ ├── src # output value ('src/api-types/')
125
+ │ ├── api-types
126
+ │ | ├── pokemon-api # output
127
+ │ | | ├── models # API schema models
128
+ │ | | ├── services # API service level with methods/url/response/request types
129
+ │ | | └── index.ts
130
+ | | └── ...
131
+ └── ...
183
132
 
184
133
 
134
+ ## Features
185
135
  ### Nullable in OpenAPI v2
186
136
  In the OpenAPI v3 spec you can create properties that can be NULL, by providing a `nullable: true` in your schema.
187
137
  However, the v2 spec does not allow you to do this. You can use the unofficial `x-nullable` in your specification
package/bin/cli.js ADDED
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env node
2
+
3
+ 'use strict';
4
+
5
+ const path = require('path');
6
+ const program = require('commander');
7
+ const pkg = require('../package.json');
8
+
9
+ const params = program
10
+ .name('codegen-openapi-ts-cli')
11
+ .usage('[options]')
12
+ .version(pkg.version)
13
+ .argument('<from>', 'Original response specification version')
14
+ .argument('<source>', 'Swagger/OpenAPI response url')
15
+ .argument('[output]', 'Output folder name', 'output')
16
+ .parse(process.argv)
17
+ .processedArgs;
18
+
19
+ const OpenAPI = require(path.resolve(__dirname, '../dist/index.js'));
20
+
21
+ if (OpenAPI) {
22
+ OpenAPI.convertAndGenerate(
23
+ {
24
+ from: params[0],
25
+ to: 'openapi_3',
26
+ source: params[1]
27
+ },
28
+ {
29
+ input: 'api-schema.json',
30
+ output: params[2],
31
+ useOptions: true,
32
+ useUnionTypes: true
33
+ },
34
+ )
35
+ }
package/bin/index.js CHANGED
@@ -1,48 +1,46 @@
1
- #!/usr/bin/env node
1
+ #!/usr/bin/env node
2
2
 
3
3
  'use strict';
4
4
 
5
5
  const path = require('path');
6
6
  const program = require('commander');
7
7
  const pkg = require('../package.json');
8
+ const OpenAPI = require(path.resolve(__dirname, '../dist/index.js'));
9
+
10
+ const appRoot = process.cwd().split('/node_modules')[0]
8
11
 
9
12
  const params = program
10
- .name('openapi')
13
+ .name('codegen-openapi-ts')
11
14
  .usage('[options]')
12
15
  .version(pkg.version)
13
- .requiredOption('-i, --input <value>', 'OpenAPI specification, can be a path, url or string content (required)')
14
- .requiredOption('-o, --output <value>', 'Output directory (required)')
15
- .option('-c, --client <value>', 'HTTP client to generate [fetch, xhr, node, axios]', 'fetch')
16
- .option('--useOptions', 'Use options instead of arguments')
17
- .option('--useUnionTypes', 'Use union types instead of enums')
18
- .option('--exportServices <value>', 'Write services to disk', true)
19
- .option('--exportModels <value>', 'Write models to disk', true)
20
- .option('--postfix <value>', 'Service name postfix', 'Service')
21
- .option('--request <value>', 'Path to custom request file')
16
+ .option('--config <value>', 'Path to config file', 'codegen.config.js')
22
17
  .parse(process.argv)
23
18
  .opts();
24
19
 
25
- const OpenAPI = require(path.resolve(__dirname, '../dist/index.js'));
20
+ async function generateOnConfig () {
21
+ try {
22
+ const configFile = require(path.join(appRoot, params.config))
26
23
 
27
- if (OpenAPI) {
28
- OpenAPI.generate({
29
- input: params.input,
30
- output: params.output,
31
- httpClient: params.client,
32
- useOptions: params.useOptions,
33
- useUnionTypes: params.useUnionTypes,
34
- exportCore: false,
35
- exportServices: JSON.parse(params.exportServices) === true,
36
- exportModels: JSON.parse(params.exportModels) === true,
37
- exportSchemas: false,
38
- postfix: params.postfix,
39
- request: params.request,
40
- })
41
- .then(() => {
42
- process.exit(0);
43
- })
44
- .catch(error => {
45
- console.error(error);
46
- process.exit(1);
47
- });
24
+ for (let i = 0; i < configFile.length; i++) {
25
+ console.log('Generating ' + configFile[i].source)
26
+ await OpenAPI.convertAndGenerate(
27
+ {
28
+ from: configFile[i].from,
29
+ to: 'openapi_3',
30
+ source: configFile[i].source
31
+ },
32
+ {
33
+ input: 'api-schema.json',
34
+ output: configFile[i].output || 'output',
35
+ useOptions: true,
36
+ useUnionTypes: true
37
+ },
38
+ configFile[i].urlMethodMapping || [],
39
+ )
40
+ }
41
+ } catch (err) {
42
+ console.log(err)
43
+ }
48
44
  }
45
+
46
+ generateOnConfig()