codegen-openapi-ts 0.3.3 → 0.3.6

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
 
@@ -16,6 +17,8 @@
16
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
21
+ - Supports fetching single file (well, technically) and generate type from that
19
22
 
20
23
  ## Install
21
24
 
@@ -26,9 +29,34 @@ npm install codegen-openapi-ts --save-dev
26
29
 
27
30
  ## Usage
28
31
 
32
+ **codegen.config.js**
29
33
  ```
30
- const OpenAPI = require('codegen-openapi-ts')
34
+ codegen-openapi-ts --help
35
+ Usage: codegen-openapi-ts [options]
36
+
37
+ Options:
38
+ -V, --version output the version number
39
+ --config <value> Path to config file (default: "codegen.config.js")
40
+ -h, --help display help for command
41
+ ```
42
+
43
+ **CLI**
44
+ ```
45
+ codegen-openapi-ts-cli --help
46
+ Usage: codegen-openapi-ts-cli [options]
47
+
48
+ Arguments:
49
+ from Original response specification version
50
+ source Swagger/OpenAPI response url
51
+ output Output folder name (default: "output")
31
52
 
53
+ Options:
54
+ -V, --version output the version number
55
+ -h, --help display help for command
56
+ ```
57
+
58
+ **Node**
59
+ ```
32
60
  OpenAPI.convertAndGenerate({
33
61
  from: string, // swagger_1, swagger_2, openapi_3, api_blueprint, io_docs, google, raml, wadl
34
62
  to: string, // swagger_1, swagger_2, openapi_3, api_blueprint, io_docs, google, raml, wadl
@@ -43,7 +71,31 @@ OpenAPI.convertAndGenerate({
43
71
 
44
72
 
45
73
  ## Example
46
- **fetch-schema.js**
74
+ **codegen.config.js**
75
+ ```javascript
76
+ 'use strict';
77
+
78
+ module.exports = [
79
+ {
80
+ source: 'http://pokemon-api/docs/api',
81
+ from: 'openapi_3',
82
+ output: 'src/api-types/pokemon-api', // pokemon-api
83
+ },
84
+ {
85
+ source: 'ssh://git@github.com/pokemon/pokemon-api.git HEAD docs/evolution-path.json',
86
+ from: 'openapi_3',
87
+ output: 'src/api-types/evolution-path', // evolution-path
88
+ },
89
+ ];
90
+ ```
91
+
92
+ **CLI**
93
+ ```bash
94
+ codegen-openapi-ts-cli swagger_2 https://pokemonapi/docs/api
95
+ codegen-openapi-ts-cli swagger_2 https://pokemonapi/docs/api pokemon-api
96
+ ```
97
+
98
+ **fetch-schema.js (Node)**
47
99
  ```javascript
48
100
  // fetch-schema.js
49
101
  const OpenAPI = require('codegen-openapi-ts')
@@ -62,9 +114,8 @@ OpenAPI.convertAndGenerate(
62
114
  }
63
115
  )
64
116
  ```
65
-
66
- **package.json**
67
117
  ```json
118
+ // package.json
68
119
  {
69
120
  "scripts": {
70
121
  "generate": "node fetch-schema.js swagger_2 https://pokemon-api/docs/api pokemon-api"
@@ -78,7 +129,7 @@ OpenAPI.convertAndGenerate(
78
129
  ├── ...
79
130
  ├── src # output value ('src/api-types/')
80
131
  │ ├── api-types
81
- │ | ├── pokemon-api # process.argv[4]
132
+ │ | ├── pokemon-api # output
82
133
  │ | | ├── models # API schema models
83
134
  │ | | ├── services # API service level with methods/url/response/request types
84
135
  │ | | └── index.ts
@@ -87,103 +138,6 @@ OpenAPI.convertAndGenerate(
87
138
 
88
139
 
89
140
  ## Features
90
-
91
- ### Enums vs. Union Types `--useUnionTypes`
92
- The OpenAPI spec allows you to define [enums](https://swagger.io/docs/specification/data-models/enums/) inside the
93
- data model. By default, we convert these enums definitions to [TypeScript enums](https://www.typescriptlang.org/docs/handbook/enums.html).
94
- 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).
95
- Because we also want to support projects that use Babel [@babel/plugin-transform-typescript](https://babeljs.io/docs/en/babel-plugin-transform-typescript),
96
- we offer the flag `--useUnionTypes` to generate [union types](https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#union-types)
97
- instead of the traditional enums. The difference can be seen below:
98
-
99
- **Enums:**
100
- ```typescript
101
- // Model
102
- export interface Order {
103
- id?: number;
104
- quantity?: number;
105
- status?: Order.status;
106
- }
107
-
108
- export namespace Order {
109
- export enum status {
110
- PLACED = 'placed',
111
- APPROVED = 'approved',
112
- DELIVERED = 'delivered',
113
- }
114
- }
115
-
116
- // Usage
117
- const order: Order = {
118
- id: 1,
119
- quantity: 40,
120
- status: Order.status.PLACED
121
- }
122
- ```
123
-
124
- **Union Types:**
125
- ```typescript
126
- // Model
127
- export interface Order {
128
- id?: number;
129
- quantity?: number;
130
- status?: 'placed' | 'approved' | 'delivered';
131
- }
132
-
133
- // Usage
134
- const order: Order = {
135
- id: 1,
136
- quantity: 40,
137
- status: 'placed'
138
- }
139
- ```
140
-
141
- ### Enum with custom names and descriptions
142
- You can use `x-enum-varnames` and `x-enum-descriptions` in your spec to generate enum with custom names and descriptions.
143
- It's not in official [spec](https://github.com/OAI/OpenAPI-Specification/issues/681) yet. But it's a supported extension
144
- that can help developers use more meaningful enumerators.
145
- ```json
146
- {
147
- "EnumWithStrings": {
148
- "description": "This is a simple enum with strings",
149
- "enum": [
150
- 0,
151
- 1,
152
- 2
153
- ],
154
- "x-enum-varnames": [
155
- "Success",
156
- "Warning",
157
- "Error"
158
- ],
159
- "x-enum-descriptions": [
160
- "Used when the status of something is successful",
161
- "Used when the status of something has a warning",
162
- "Used when the status of something has an error"
163
- ]
164
- }
165
- }
166
- ```
167
-
168
- Generated code:
169
- ```typescript
170
- enum EnumWithStrings {
171
- /*
172
- * Used when the status of something is successful
173
- */
174
- Success = 0,
175
- /*
176
- * Used when the status of something has a warning
177
- */
178
- Waring = 1,
179
- /*
180
- * Used when the status of something has an error
181
- */
182
- Error = 2,
183
- }
184
- ```
185
-
186
-
187
141
  ### Nullable in OpenAPI v2
188
142
  In the OpenAPI v3 spec you can create properties that can be NULL, by providing a `nullable: true` in your schema.
189
143
  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()