Skip to content

Commit a14c188

Browse files
authored
Add OpenAPI3 primitives (#180)
* Add test file for primitives * Support OpenAPI3 primitives
1 parent d31f99e commit a14c188

31 files changed

+11750
-6615
lines changed

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
.cache
22
.DS_Store
3-
*.ts.snap
3+
./generated/*.ts
44
coverage
55
pkg
66
node_modules

.prettierrc

Lines changed: 0 additions & 6 deletions
This file was deleted.

README.md

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,16 @@
44

55
# 📘️ swagger-to-ts
66

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

99
💅 The output is prettified with [Prettier][prettier].
1010

1111
👉 Works for both local and remote resources (filesystem and http).
1212

1313
To compare actual generated output, see the [example](./example) folder.
1414

15-
(**swagger-to-ts** can handle large definition files within milliseconds because it neither validates nor parses; it only transforms the bare minimum of what it needs to.)
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.)
1617

1718
## Usage
1819

@@ -54,9 +55,10 @@ For anything more complicated, or for generating specs dynamically, you can also
5455

5556
#### CLI Options
5657

57-
| Option | Alias | Default | Description |
58-
| :-------------------- | :---- | :------: | :------------------------------------- |
59-
| `--output [location]` | `-o` | (stdout) | Where should the output file be saved? |
58+
| Option | Alias | Default | Description |
59+
| :----------------------------- | :---- | :------: | :--------------------------------------------------------------- |
60+
| `--output [location]` | `-o` | (stdout) | Where should the output file be saved? |
61+
| `--prettier-config [location]` | | | (optional) Path to your custom Prettier configuration for output |
6062

6163
### Node
6264

@@ -99,10 +101,12 @@ const getNullable = (d: { [key: string]: any }): boolean => {
99101
return true;
100102
};
101103

102-
const output = swaggerToTS(swagger, (swaggerDefinition, property): Property => ({
103-
...property,
104-
optional: getNullable(swaggerDefinition),
105-
}));
104+
const output = swaggerToTS(swagger, {
105+
propertyMapper: (swaggerDefinition, property): Property => ({
106+
...property,
107+
optional: getNullable(swaggerDefinition),
108+
}),
109+
});
106110
```
107111

108112
[glob]: https://www.npmjs.com/package/glob

bin/cli.js

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
#!/usr/bin/env node
22

3-
const { writeFileSync } = require('fs');
4-
const { mkdirpSync } = require('fs-extra');
5-
const chalk = require('chalk');
6-
const { dirname, resolve } = require('path');
7-
const meow = require('meow');
8-
const { default: swaggerToTS } = require('../dist-node');
9-
const { loadSpec } = require('./loaders');
3+
const fs = require("fs-extra");
4+
const chalk = require("chalk");
5+
const path = require("path");
6+
const meow = require("meow");
7+
const { default: swaggerToTS } = require("../dist-node");
8+
const { loadSpec } = require("./loaders");
109

1110
const cli = meow(
1211
`Usage
@@ -15,12 +14,16 @@ const cli = meow(
1514
Options
1615
--help display this
1716
--output, -o specify output file
17+
--prettier-config (optional) specify path to Prettier config file
1818
`,
1919
{
2020
flags: {
2121
output: {
22-
type: 'string',
23-
alias: 'o',
22+
type: "string",
23+
alias: "o",
24+
},
25+
prettierConfig: {
26+
type: "string",
2427
},
2528
},
2629
}
@@ -30,7 +33,7 @@ const pathToSpec = cli.input[0];
3033
const timeStart = process.hrtime();
3134

3235
(async () => {
33-
let spec = '';
36+
let spec = "";
3437
try {
3538
spec = await loadSpec(pathToSpec);
3639
} catch (e) {
@@ -41,14 +44,18 @@ const timeStart = process.hrtime();
4144

4245
// Write to file if specifying output
4346
if (cli.flags.output) {
44-
const outputFile = resolve(process.cwd(), cli.flags.output);
45-
const parent = dirname(outputFile);
46-
mkdirpSync(parent);
47-
writeFileSync(outputFile, result);
47+
const outputFile = path.resolve(process.cwd(), cli.flags.output);
48+
const parent = path.dirname(outputFile);
49+
fs.mkdirpSync(parent);
50+
fs.writeFileSync(outputFile, result, "utf8");
4851

4952
const timeEnd = process.hrtime(timeStart);
5053
const time = timeEnd[0] + Math.round(timeEnd[1] / 1e6);
51-
console.log(chalk.green(`🚀 ${cli.input[0]} -> ${chalk.bold(cli.flags.output)} [${time}ms]`));
54+
console.log(
55+
chalk.green(
56+
`🚀 ${cli.input[0]} -> ${chalk.bold(cli.flags.output)} [${time}ms]`
57+
)
58+
);
5259
return;
5360
}
5461

bin/loaders/index.js

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
const yaml = require('js-yaml');
2-
const chalk = require('chalk');
1+
const yaml = require("js-yaml");
2+
const chalk = require("chalk");
33

4-
const loadFromFs = require('./loadFromFs');
5-
const loadFromHttp = require('./loadFromHttp');
4+
const loadFromFs = require("./loadFromFs");
5+
const loadFromHttp = require("./loadFromHttp");
66

77
async function load(pathToSpec) {
88
let rawSpec;
@@ -15,24 +15,30 @@ async function load(pathToSpec) {
1515
}
1616

1717
function isYamlSpec(rawSpec, pathToSpec) {
18-
return /\.ya?ml$/i.test(pathToSpec) || rawSpec[0] !== '{';
18+
return /\.ya?ml$/i.test(pathToSpec) || rawSpec[0] !== "{";
1919
}
2020

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

2527
try {
2628
if (isYamlSpec(rawSpec, pathToSpec)) {
2729
return yaml.safeLoad(rawSpec);
2830
}
2931
} catch {
30-
throw new Error(`The spec under ${pathToSpec} seems to be YAML, but it couldn’t be parsed.`);
32+
throw new Error(
33+
`The spec under ${pathToSpec} seems to be YAML, but it couldn’t be parsed.`
34+
);
3135
}
3236

3337
try {
3438
return JSON.parse(rawSpec);
3539
} catch {
36-
throw new Error(`The spec under ${pathToSpec} couldn’t be parsed neither as YAML nor JSON.`);
40+
throw new Error(
41+
`The spec under ${pathToSpec} couldn’t be parsed neither as YAML nor JSON.`
42+
);
3743
}
3844
};

bin/loaders/loadFromFs.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
1-
const { resolve } = require('path');
2-
const { existsSync, readFile } = require('fs');
1+
const fs = require("fs");
2+
const path = require("path");
33

44
module.exports = (pathToSpec) => {
5-
const pathname = resolve(process.cwd(), pathToSpec);
6-
const pathExists = existsSync(pathname);
5+
const pathname = path.resolve(process.cwd(), pathToSpec);
6+
const pathExists = fs.existsSync(pathname);
77

88
return new Promise((resolve, reject) => {
99
if (pathExists) {
10-
readFile(pathname, 'UTF-8', (err, data) => {
10+
fs.readFile(pathname, "UTF-8", (err, data) => {
1111
if (err) {
1212
reject(err);
1313
}

bin/loaders/loadFromHttp.js

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
const url = require('url');
1+
const url = require("url");
22
const adapters = {
3-
'http:': require('http'),
4-
'https:': require('https'),
3+
"http:": require("http"),
4+
"https:": require("https"),
55
};
66

77
function fetchFrom(inputUrl) {
@@ -11,7 +11,7 @@ function fetchFrom(inputUrl) {
1111
function buildOptions(pathToSpec) {
1212
const requestUrl = url.parse(pathToSpec);
1313
return {
14-
method: 'GET',
14+
method: "GET",
1515
hostname: requestUrl.host,
1616
path: requestUrl.path,
1717
};
@@ -21,16 +21,16 @@ module.exports = (pathToSpec) => {
2121
return new Promise((resolve, reject) => {
2222
const opts = buildOptions(pathToSpec);
2323
const req = fetchFrom(pathToSpec).request(opts, (res) => {
24-
let rawData = '';
25-
res.setEncoding('utf8');
26-
res.on('data', (chunk) => {
24+
let rawData = "";
25+
res.setEncoding("utf8");
26+
res.on("data", (chunk) => {
2727
rawData += chunk;
2828
});
29-
res.on('end', () => {
29+
res.on("end", () => {
3030
resolve(rawData);
3131
});
3232
});
33-
req.on('error', (err) => {
33+
req.on("error", (err) => {
3434
reject(err);
3535
});
3636
req.end();

0 commit comments

Comments
 (0)