Skip to content

Commit 37fd03f

Browse files
authored
Add test for --prettier-config (#202)
* Add test for --prettier-config Also add README section * Improve README
1 parent 556267c commit 37fd03f

File tree

13 files changed

+11841
-1611
lines changed

13 files changed

+11841
-1611
lines changed

README.md

Lines changed: 146 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -4,54 +4,61 @@
44

55
# 📘️ swagger-to-ts
66

7-
🚀 Convert [OpenAPI v2][openapi2] schemas to TypeScript interfaces using Node.js.
7+
🚀 Convert [OpenAPI 2.0][openapi2] and [OpenAPI 3.0][openapi3] schemas to TypeScript interfaces using Node.js.
88

9-
💅 The output is prettified with [Prettier][prettier].
9+
💅 The output is prettified with [Prettier][prettier] (and can be customized!).
1010

11-
👉 Works for both local and remote resources (filesystem and http).
11+
👉 Works for both local and remote resources (filesystem and HTTP).
1212

13-
To compare actual generated output, see the [example](./example) folder.
13+
View examples:
1414

15-
(**swagger-to-ts** can handle large definition files within milliseconds because it neither
16-
validates nor parses; it only transforms the bare minimum of what it needs to.)
15+
- [Stripe, OpenAPI 2.0](./examples/stripe-openapi2.ts)
16+
- [Stripe, OpenAPI 3.0](./examples/stripe-openapi3.ts)
1717

1818
## Usage
1919

2020
### CLI
2121

22-
#### Reading specs from file system
22+
#### 🗄️ Reading specs from file system
2323

2424
```bash
25-
npx @manifoldco/swagger-to-ts schema.yaml --output schema.d.ts
25+
npx @manifoldco/swagger-to-ts schema.yaml --output schema.ts
26+
27+
# 🤞 Loading spec from tests/v2/specs/stripe.yaml…
28+
# 🚀 schema.yaml -> schema.ts [250ms]
2629
```
2730

28-
#### Reading specs from remote resource
31+
#### ☁️ Reading specs from remote resource
2932

3033
```bash
31-
npx @manifoldco/swagger-to-ts https://petstore.swagger.io/v2/swagger.json --output petstore.d.ts
32-
```
34+
npx @manifoldco/swagger-to-ts https://petstore.swagger.io/v2/swagger.json --output petstore.ts
3335

34-
This will save a `schema.d.ts` file in the current folder under the TypeScript
35-
[namespace][namespace] `OpenAPI` (namespaces are required because chances of collision among specs
36-
is highly likely). The CLI can accept YAML or JSON for the input file.
36+
# 🤞 Loading spec from https://petstore.swagger.io/v2/swagger.json…
37+
# 🚀 https://petstore.swagger.io/v2/swagger.json -> petstore.ts [650ms]
38+
```
3739

3840
#### Generating multiple schemas
3941

40-
Say you have multiple schemas you need to parse. I’ve found the simplest way to do that is to use
41-
npm scripts. In your `package.json`, you can do something like the following:
42+
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:
4243

4344
```json
4445
"scripts": {
45-
"generate:specs": "npm run generate:specs:one && npm run generate:specs:two",
46-
"generate:specs:one": "npx @manifoldco/swagger-to-ts one.yaml -o one.d.ts",
47-
"generate:specs:two": "npx @manifoldco/swagger-to-ts two.yaml -o two.d.ts"
46+
"generate:specs": "npm run generate:specs:one && npm run generate:specs:two && npm run generate:specs:three",
47+
"generate:specs:one": "npx @manifoldco/swagger-to-ts one.yaml -o one.ts",
48+
"generate:specs:two": "npx @manifoldco/swagger-to-ts two.yaml -o two.ts",
49+
"generate:specs:three": "npx @manifoldco/swagger-to-ts three.yaml -o three.ts"
4850
}
4951
```
5052

53+
You can even specify unique options per-spec, if needed. To generate them all together, run:
54+
55+
```bash
56+
npm run generate:specs
57+
```
58+
5159
Rinse and repeat for more specs.
5260

53-
For anything more complicated, or for generating specs dynamically, you can also use the Node API
54-
(below).
61+
For anything more complicated, or for generating specs dynamically, you can also use the [Node API](#node).
5562

5663
#### CLI Options
5764

@@ -109,6 +116,124 @@ const output = swaggerToTS(swagger, {
109116
});
110117
```
111118

119+
## Upgrading from v1 to v2
120+
121+
Some options were removed in swagger-to-ts v2 that will break apps using v1, but it does so in exchange for more control, more stability, and more resilient types.
122+
123+
TL;DR:
124+
125+
```diff
126+
-import { OpenAPI2 } from './generated';
127+
+import { definitions } from './generated';
128+
129+
-type MyType = OpenAPI2.MyType;
130+
+type MyType = definitions['MyType'];
131+
```
132+
133+
#### In-depth explanation
134+
135+
In order to explain the change, let’s go through an example with the following Swagger definition (partial):
136+
137+
```yaml
138+
swagger: 2.0
139+
definitions:
140+
user:
141+
type: object
142+
properties:
143+
role:
144+
type: object
145+
properties:
146+
access:
147+
enum:
148+
- admin
149+
- user
150+
user_role:
151+
type: object
152+
role:
153+
type: string
154+
team:
155+
type: object
156+
properties:
157+
users:
158+
type: array
159+
items:
160+
$ref: user
161+
```
162+
163+
This is how **v1** would have generated those types:
164+
165+
```ts
166+
declare namespace OpenAPI2 {
167+
export interface User {
168+
role?: UserRole;
169+
}
170+
export interface UserRole {
171+
access?: "admin" | "user";
172+
}
173+
export interface UserRole {
174+
role?: string;
175+
}
176+
export interface Team {
177+
users?: User[];
178+
}
179+
}
180+
```
181+
182+
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.
183+
184+
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:
185+
186+
```ts
187+
export interface definitions {
188+
user: {
189+
role?: {
190+
access?: "admin" | "user";
191+
};
192+
};
193+
user_role: {
194+
role?: string;
195+
};
196+
team: {
197+
users?: definitions["user"][];
198+
};
199+
}
200+
```
201+
202+
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:
203+
204+
```diff
205+
-UserRole
206+
+definitions['user']['role'];
207+
```
208+
209+
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.
210+
211+
#### Better \$ref generation
212+
213+
swagger-to-ts 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.
214+
215+
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 swagger-to-ts, which is a better approach in general.
216+
217+
#### No Wrappers
218+
219+
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:
220+
221+
```ts
222+
import { components as Schema1 } from './generated/schema-1.ts';
223+
import { components as Schema2 } from './generated/schema-2.ts';
224+
225+
declare namespace OpenAPI3 {
226+
export Schema1;
227+
export Schema2;
228+
}
229+
```
230+
231+
#### No CamelCasing
232+
233+
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).
234+
235+
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.
236+
112237
[glob]: https://www.npmjs.com/package/glob
113238
[js-yaml]: https://www.npmjs.com/package/js-yaml
114239
[openapi2]: https://swagger.io/specification/v2/

bin/cli.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,9 @@ const timeStart = process.hrtime();
4040
console.error(chalk.red(`❌ "${e}"`));
4141
}
4242

43-
const result = swaggerToTS(spec);
43+
const result = swaggerToTS(spec, {
44+
prettierConfig: cli.flags.prettierConfig,
45+
});
4446

4547
// Write to file if specifying output
4648
if (cli.flags.output) {

bin/loaders/index.js

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,7 @@ function isYamlSpec(rawSpec, pathToSpec) {
1919
}
2020

2121
module.exports.loadSpec = async (pathToSpec) => {
22-
console.log(
23-
chalk.yellow(`🤞 Loading spec from ${chalk.bold(pathToSpec)}...`)
24-
);
22+
console.log(chalk.yellow(`🤞 Loading spec from ${chalk.bold(pathToSpec)}…`));
2523
const rawSpec = await load(pathToSpec);
2624

2725
try {

0 commit comments

Comments
 (0)