@@ -7,7 +7,18 @@ Node script that can convert Swagger files to TypeScript interfaces. This uses
77npm i --save-dev @manifoldco/swagger-to-ts
88```
99
10- ### Generating
10+ ### Usage
11+
12+ The function takes 2 parameters: a ** filepath** (` ./path/to/my/spec.json ` ),
13+ and a ** namespace** ('MySpec'). Namespace is required because it’s very
14+ likely entities within the Swagger spec will collide with some other type in
15+ your system, but you still want to access something predictably-named.
16+
17+ ``` js
18+ const swaggerToTS = require (' swagger-to-ts' );
19+
20+ const typeData = swaggerToJS (' ./path/to/my/spec.json' , ' MySpec' );
21+ ```
1122
1223#### From Swagger JSON
1324
@@ -16,10 +27,14 @@ const { readFileSync, writeFileSync } = require('fs');
1627const swaggerToTS = require (' swagger-to-ts' );
1728
1829const file = ' ./spec/swagger.json' ;
19- const typeData = swaggerToTS (readFileSync (file, ' UTF-8' ));
30+ const typeData = swaggerToTS (readFileSync (file, ' UTF-8' ), ' MySpec ' );
2031writeFileSync (' ./types/swagger.ts' ), typeData);
2132```
2233
34+ ``` js
35+ import MySpec from ' ./types/swagger.ts' ;
36+ ```
37+
2338#### From Swagger YAML
2439
2540Swagger files must be passed to ` swaggerToTS() ` in a JSON format, so you’ll
@@ -31,10 +46,14 @@ const { readFileSync, writeFileSync } = require('fs');
3146const yaml = require (' js-yaml' );
3247
3348const file = ' ./spec/swagger.json' ;
34- const typeData = swaggerToTS (yaml .safeLoad (fs .readFileSync (file, ' UTF-8' )));
49+ const typeData = swaggerToTS (yaml .safeLoad (fs .readFileSync (file, ' UTF-8' )), ' MySpec ' );
3550writeFileSync (' ./types/swagger.ts' ), typeData);
3651```
3752
53+ ``` js
54+ import MySpec from ' ./types/swagger.ts' ;
55+ ```
56+
3857#### Generating multiple files
3958
4059The [ glob] [ glob ] package is helpful in converting entire folders. The
@@ -50,8 +69,12 @@ const source1 = glob.sync('./swaggerspec/v1/**/*.yaml');
5069const source2 = glob .sync (' ./swaggerspec/v2/**/*.yaml' );
5170
5271[... source1, ... source2].forEach (file => {
53- const typeData = swaggerToTS (yaml .safeLoad (readFileSync (file, ' UTF-8' )));
54- const filename = path .basename (file).replace (/ \. ya? ml$ / i , ' .ts' );
72+ const basename = path .basename (file);
73+ const filename = basename .replace (/ \. ya? ml$ / i , ' .ts' );
74+ const typeData = swaggerToTS (
75+ yaml .safeLoad (readFileSync (file, ' UTF-8' )),
76+ basename
77+ );
5578 writeFileSync (path .resolve (__dirname , ' types' , filename), typeData);
5679});
5780```
@@ -94,9 +117,9 @@ It’s recommended to name the file `*.ts` and `import` the definitions. `*.d.ts
94117can’t be imported; they’re meant to be shipped alongside modules.
95118
96119``` js
97- import { User } from ' ../types/swagger' ;
120+ import Swagger from ' ../types/swagger' ;
98121
99- const logIn = (user : User ) => {
122+ const logIn = (user : Swagger . User ) => {
100123 // …
101124` ` `
102125
0 commit comments