You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
🚀 Convert [OpenAPI 3.0][openapi3] and [OpenAPI 2.0 (Swagger)][openapi2] schemas to TypeScript interfaces using Node.js.
12
+
🚀 Convert [OpenAPI 3.0][openapi3] and [2.0 (Swagger)][openapi2] schemas to TypeScript interfaces using Node.js.
11
13
12
14
💅 The output is prettified with [Prettier][prettier] (and can be customized!).
13
15
@@ -44,7 +46,8 @@ _Thanks to @psmyrdek for this feature!_
44
46
45
47
#### Generating multiple schemas
46
48
47
-
In your `package.json`, for each schema you’d like to transform add one `generate:specs:[name]` npm-script. Then combine them all into one `generate:specs` script, like so:
49
+
In your `package.json`, for each schema you’d like to transform add one `generate:specs:[name]` npm-script. Then combine
50
+
them all into one `generate:specs` script, like so:
48
51
49
52
```json
50
53
"scripts": {
@@ -55,6 +58,13 @@ In your `package.json`, for each schema you’d like to transform add one `gener
55
58
}
56
59
```
57
60
61
+
If you use [npm-run-all][npm-run-all], you can shorten this:
62
+
63
+
```json
64
+
"scripts": {
65
+
"generate:specs": "run-p generate:specs:*",
66
+
```
67
+
58
68
You can even specify unique options per-spec, if needed. To generate them all together, run:
59
69
60
70
```bash
@@ -86,21 +96,20 @@ const input = JSON.parse(readFileSync("spec.json", "utf8")); // Input can be any
86
96
const output = swaggerToTS(input); // Outputs TypeScript defs as a string (to be parsed, or written to a file)
87
97
```
88
98
89
-
The Node API is a bit more flexible: it will only take a JS object as input (OpenAPI format), and
90
-
return a string of TS definitions. This lets you pull from any source (a Swagger server, local
91
-
files, etc.), and similarly lets you parse, post-process, and save the output anywhere.
99
+
The Node API is a bit more flexible: it will only take a JS object as input (OpenAPI format), and return a string of TS
100
+
definitions. This lets you pull from any source (a Swagger server, local files, etc.), and similarly lets you parse,
101
+
post-process, and save the output anywhere.
92
102
93
-
If your specs are in YAML, you’ll have to convert them to JS objects using a library such as
94
-
[js-yaml][js-yaml]. If you’re batching large folders of specs, [glob][glob] may also come in handy.
103
+
If your specs are in YAML, you’ll have to convert them to JS objects using a library such as[js-yaml][js-yaml]. If
104
+
you’re batching large folders of specs, [glob][glob] may also come in handy.
95
105
96
106
#### PropertyMapper
97
107
98
-
In order to allow more control over how properties are parsed, and to specifically handle
99
-
`x-something`-properties, the `propertyMapper` option may be specified as the optional 2nd
100
-
parameter.
108
+
In order to allow more control over how properties are parsed, and to specifically handle `x-something`-properties, the
109
+
`propertyMapper` option may be specified as the optional 2nd parameter.
101
110
102
-
This is a function that, if specified, is called for each property and allows you to change how
103
-
openapi-typescript handles parsing of Swagger files.
111
+
This is a function that, if specified, is called for each property and allows you to change how openapi-typescript
112
+
handles parsing of Swagger files.
104
113
105
114
An example on how to use the `x-nullable` property to control if a property is optional:
Some options were removed in openapi-typescript v2 that will break apps using v1, but it does so in exchange for more control, more stability, and more resilient types.
129
-
130
-
TL;DR:
131
-
132
-
```diff
133
-
-import { OpenAPI2 } from './generated';
134
-
+import { definitions } from './generated';
135
+
## Migrating from v1 to v2
135
136
136
-
-type MyType = OpenAPI2.MyType;
137
-
+type MyType = definitions['MyType'];
138
-
```
137
+
[Migrating from v1 to v2](./docs/migrating-from-v1.md)
139
138
140
-
#### In-depth explanation
141
-
142
-
In order to explain the change, let’s go through an example with the following Swagger definition (partial):
143
-
144
-
```yaml
145
-
swagger: 2.0
146
-
definitions:
147
-
user:
148
-
type: object
149
-
properties:
150
-
role:
151
-
type: object
152
-
properties:
153
-
access:
154
-
enum:
155
-
- admin
156
-
- user
157
-
user_role:
158
-
type: object
159
-
role:
160
-
type: string
161
-
team:
162
-
type: object
163
-
properties:
164
-
users:
165
-
type: array
166
-
items:
167
-
$ref: user
168
-
```
139
+
## Project Goals
169
140
170
-
This is how **v1** would have generated those types:
141
+
1. Support converting any OpenAPI 3.0 or 2.0 (Swagger) schema to TypeScript types, no matter how complicated
142
+
1. The generated TypeScript types **must** match your schema as closely as possible (i.e. don’t convert names to
143
+
`PascalCase` or follow any TypeScript-isms; faithfully reproduce your schema as closely as possible, capitalization
144
+
and all)
145
+
1. This library is a TypeScript generator, not a schema validator.
171
146
172
-
```ts
173
-
declare namespace OpenAPI2 {
174
-
export interface User {
175
-
role?: UserRole;
176
-
}
177
-
export interface UserRole {
178
-
access?: "admin"| "user";
179
-
}
180
-
export interface UserRole {
181
-
role?: string;
182
-
}
183
-
export interface Team {
184
-
users?: User[];
185
-
}
186
-
}
187
-
```
147
+
## Contributing
188
148
189
-
Uh oh. It tried to be intelligent, and keep interfaces shallow by transforming `user.role` into `UserRole.` However, we also have another `user_role` entry that has a conflicting `UserRole` interface. This is not what we want.
190
-
191
-
v1 of this project made certain assumptions about your schema that don’t always hold true. This is how **v2** generates types from that same schema:
192
-
193
-
```ts
194
-
exportinterfacedefinitions {
195
-
user: {
196
-
role?: {
197
-
access?:"admin"|"user";
198
-
};
199
-
};
200
-
user_role: {
201
-
role?:string;
202
-
};
203
-
team: {
204
-
users?:definitions["user"][];
205
-
};
206
-
}
207
-
```
208
-
209
-
This matches your schema more accurately, and doesn’t try to be clever by keeping things shallow. It’s also more predictable, with the generated types matching your schema naming. In your code here’s what would change:
210
-
211
-
```diff
212
-
-UserRole
213
-
+definitions['user']['role'];
214
-
```
215
-
216
-
While this is a change, it’s more predictable. Now you don’t have to guess what `user_role` was renamed to; you simply chain your type from the Swagger definition you‘re used to.
217
-
218
-
#### Better \$ref generation
219
-
220
-
openapi-typescript v1 would attempt to resolve and flatten `$ref`s. This was bad because it would break on circular references (which both Swagger and TypeScript allow), and resolution also slowed it down.
221
-
222
-
In v2, your `$ref`s are preserved as-declared, and TypeScript does all the work. Now the responsibility is on your schema to handle collisions rather than openapi-typescript, which is a better approach in general.
223
-
224
-
#### No Wrappers
225
-
226
-
The `--wrapper` CLI flag was removed because it was awkward having to manage part of your TypeScript definition in a CLI flag. In v2, simply compose the wrapper yourself however you’d like in TypeScript:
The `--camelcase` flag was removed because it would mangle object names incorrectly or break trying to sanitize them (for example, you couldn’t run camelcase on a schema with `my.obj` and `my-obj`—they both would transfom to the same thing causing unexpected results).
241
-
242
-
OpenAPI allows for far more flexibility in naming schema objects than JavaScript, so that should be carried over from your schema. In v2, the naming of generated types maps 1:1 with your schema name.
149
+
PRs are welcome! Please see our [CONTRIBUTING.md](./CONTRIBUTING.md) guide. Opening an issue beforehand to discuss is
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
254
163
@@ -291,6 +200,8 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
291
200
292
201
<!-- markdownlint-enable -->
293
202
<!-- prettier-ignore-end -->
203
+
294
204
<!-- ALL-CONTRIBUTORS-LIST:END -->
295
205
296
-
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
206
+
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification.
Copy file name to clipboardExpand all lines: bin/loaders/index.js
+5-5
Original file line number
Diff line number
Diff line change
@@ -10,8 +10,10 @@ async function load(pathToSpec) {
10
10
try{
11
11
rawSpec=awaitloadFromHttp(pathToSpec);
12
12
}catch(e){
13
-
if(e.code==='ENOTFOUND'){
14
-
thrownewError(`The URL ${pathToSpec} could not be reached. Ensure the URL is correct, that you're connected to the internet and that the URL is reachable via a browser.`)
13
+
if(e.code==="ENOTFOUND"){
14
+
thrownewError(
15
+
`The URL ${pathToSpec} could not be reached. Ensure the URL is correct, that you're connected to the internet and that the URL is reachable via a browser.`
0 commit comments