Skip to content

Commit c02e054

Browse files
authored
Support stdout (#387)
* Allow writing to stdout * Fix CLI tests * Update README
1 parent 75fed40 commit c02e054

13 files changed

+10850
-122
lines changed

README.md

+9
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22
[![codecov](https://codecov.io/gh/drwpow/openapi-typescript/branch/master/graph/badge.svg)](https://codecov.io/gh/drwpow/openapi-typescript)
33

44
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
5+
56
[![All Contributors](https://img.shields.io/badge/all_contributors-24-orange.svg?style=flat-square)](#contributors-)
7+
68
<!-- ALL-CONTRIBUTORS-BADGE:END -->
79

810
# 📘️ openapi-typescript
@@ -42,6 +44,12 @@ npx openapi-typescript https://petstore.swagger.io/v2/swagger.json --output pets
4244

4345
_Thanks to @psmyrdek for this feature!_
4446

47+
#### Outputting to `stdout`
48+
49+
```bash
50+
npx openapi-typescript schema.yaml
51+
```
52+
4553
#### Generating multiple schemas
4654

4755
In your `package.json`, for each schema you’d like to transform add one `generate:specs:[name]` npm-script. Then combine
@@ -199,6 +207,7 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
199207

200208
<!-- markdownlint-enable -->
201209
<!-- prettier-ignore-end -->
210+
202211
<!-- ALL-CONTRIBUTORS-LIST:END -->
203212

204213
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification.

bin/cli.js

+29-16
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ const cli = meow(
1313
1414
Options
1515
--help display this
16-
--output, -o specify output file
16+
--output, -o (optional) specify output file (default: stdout)
1717
--prettier-config (optional) specify path to Prettier config file
1818
--raw-schema (optional) Read from raw schema instead of document
1919
--version (optional) Schema version (must be present for raw schemas)
@@ -37,28 +37,38 @@ Options
3737
}
3838
);
3939

40-
console.info(chalk.bold(`✨ openapi-typescript ${require("../package.json").version}`));
41-
42-
const pathToSpec = cli.input[0];
4340
const timeStart = process.hrtime();
4441

45-
(async () => {
46-
let spec = "";
42+
async function main() {
43+
let output = "FILE"; // FILE or STDOUT
44+
const pathToSpec = cli.input[0];
45+
46+
// 0. setup
47+
if (!cli.flags.output) {
48+
output = "STDOUT"; // if --output not specified, fall back to stdout
49+
}
50+
if (output === "FILE") {
51+
console.info(chalk.bold(`✨ openapi-typescript ${require("../package.json").version}`)); // only log if we’re NOT writing to stdout
52+
}
53+
54+
// 1. input
55+
let spec = undefined;
4756
try {
48-
spec = await loadSpec(pathToSpec);
49-
} catch (e) {
50-
console.error(chalk.red(`❌ "${e}"`));
51-
return;
57+
spec = await loadSpec(pathToSpec, { log: output !== "STDOUT" });
58+
} catch (err) {
59+
throw new Error(chalk.red(`❌ ${err}`));
5260
}
5361

62+
// 2. generate schema (the main part!)
5463
const result = swaggerToTS(spec, {
5564
prettierConfig: cli.flags.prettierConfig,
5665
rawSchema: cli.flags.rawSchema,
5766
version: cli.flags.version,
5867
});
5968

60-
// Write to file if specifying output
61-
if (cli.flags.output) {
69+
// 3. output
70+
if (output === "FILE") {
71+
// output option 1: file
6272
const outputFile = path.resolve(process.cwd(), cli.flags.output);
6373

6474
// recursively create parent directories if they don’t exist
@@ -74,10 +84,13 @@ const timeStart = process.hrtime();
7484

7585
const timeEnd = process.hrtime(timeStart);
7686
const time = timeEnd[0] + Math.round(timeEnd[1] / 1e6);
77-
console.log(chalk.green(`🚀 ${cli.input[0]} -> ${chalk.bold(cli.flags.output)} [${time}ms]`));
78-
return;
87+
console.log(chalk.green(`🚀 ${pathToSpec} -> ${chalk.bold(cli.flags.output)} [${time}ms]`));
88+
} else {
89+
// output option 2: stdout
90+
process.stdout.write(result);
7991
}
8092

81-
// Otherwise, return result
8293
return result;
83-
})();
94+
}
95+
96+
main();

bin/loaders/index.js

+10-7
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,11 @@ const loadFromFs = require("./loadFromFs");
55
const loadFromHttp = require("./loadFromHttp");
66

77
async function load(pathToSpec) {
8-
let rawSpec;
8+
// option 1: remote URL
99
if (/^https?:\/\//.test(pathToSpec)) {
1010
try {
11-
rawSpec = await loadFromHttp(pathToSpec);
11+
const rawSpec = await loadFromHttp(pathToSpec);
12+
return rawSpec;
1213
} catch (e) {
1314
if (e.code === "ENOTFOUND") {
1415
throw new Error(
@@ -17,18 +18,20 @@ async function load(pathToSpec) {
1718
}
1819
throw e;
1920
}
20-
} else {
21-
rawSpec = await loadFromFs(pathToSpec);
2221
}
23-
return rawSpec;
22+
23+
// option 2: local file
24+
return loadFromFs(pathToSpec);
2425
}
2526

2627
function isYamlSpec(rawSpec, pathToSpec) {
2728
return /\.ya?ml$/i.test(pathToSpec) || rawSpec[0] !== "{";
2829
}
2930

30-
module.exports.loadSpec = async (pathToSpec) => {
31-
console.log(chalk.yellow(`🤞 Loading spec from ${chalk.bold(pathToSpec)}…`));
31+
module.exports.loadSpec = async (pathToSpec, { log = true }) => {
32+
if (log === true) {
33+
console.log(chalk.yellow(`🤞 Loading spec from ${chalk.bold(pathToSpec)}…`)); // only log if not writing to stdout
34+
}
3235
const rawSpec = await load(pathToSpec);
3336

3437
try {

bin/loaders/loadFromFs.js

+5-12
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,9 @@ module.exports = (pathToSpec) => {
55
const pathname = path.resolve(process.cwd(), pathToSpec);
66
const pathExists = fs.existsSync(pathname);
77

8-
return new Promise((resolve, reject) => {
9-
if (pathExists) {
10-
fs.readFile(pathname, "UTF-8", (err, data) => {
11-
if (err) {
12-
reject(err);
13-
}
14-
resolve(data);
15-
});
16-
} else {
17-
reject(`Cannot find spec under the following path: ${pathname}`);
18-
}
19-
});
8+
if (!pathExists) {
9+
throw new Error(`Cannot find spec under the following path: ${pathname}`);
10+
}
11+
12+
return fs.readFileSync(pathname, "utf8");
2013
};

jest.config.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
module.exports = {
2-
preset: 'ts-jest',
3-
testEnvironment: 'node',
2+
preset: "ts-jest",
3+
testEnvironment: "node",
44
};

0 commit comments

Comments
 (0)