Skip to content

Add --version flag, add CLI tests #970

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 5 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,8 @@ The following flags can be appended to the CLI command.

| Option | Alias | Default | Description |
| :----------------------------- | :---- | :------: | :--------------------------------------------------------------------------------------------------------------------------- |
| `--help` | | | Display inline help message and exit |
| `--version` | | | Display this library’s version and exit |
| `--output [location]` | `-o` | (stdout) | Where should the output file be saved? |
| `--auth [token]` | | | Provide an auth token to be passed along in the request (only if accessing a private schema) |
| `--header` | `-x` | | Provide an array of or singular headers as an alternative to a JSON object. Each header must follow the `key: value` pattern |
Expand Down Expand Up @@ -271,16 +273,10 @@ By default, openapiTS will generate `updated_at?: string;` because it’s not su

```js
const types = openapiTS(mySchema, {
/** transform: runs before Schema Object is converted into a TypeScript type */
transform(node: SchemaObject, options): string {
if ("format" in node && node.format === "date-time") {
return "Date"; // return the TypeScript “Date” type, as a string
return "Date";
}
// if no string returned, handle it normally
},
/** post-transform: runs after TypeScript type has been transformed */
postTransform(type: string, options): string {
// if no string returned, keep TypeScript type as-is
},
});
```
Expand All @@ -289,6 +285,8 @@ This will generate `updated_at?: Date` instead. Note that you will still have to

There are many other uses for this besides checking `format`. Because this must return a **string** you can produce any arbitrary TypeScript code you’d like (even your own custom types).

✨ Don’t forget about `postTransform()` as well! It works the same way, but runs _after_ the TypeScript transformation so you can extend/modify types as-needed.

## 🏅 Project Goals

1. Support converting any valid OpenAPI schema to TypeScript types, no matter how complicated.
Expand Down
36 changes: 21 additions & 15 deletions bin/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ const HELP = `Usage
$ openapi-typescript [input] [options]

Options
--help display this
--help Display this
--version Display the version
--output, -o Specify output file (default: stdout)
--auth (optional) Provide an authentication token for private URL
--headersObject, -h (optional) Provide a JSON object as string of HTTP headers for remote schema request
Expand Down Expand Up @@ -42,13 +43,15 @@ function errorAndExit(errorMessage) {
throw new Error(errorMessage);
}

const [, , input, ...args] = process.argv;
const [, , ...args] = process.argv;
if (args.includes("-ap")) errorAndExit(`The -ap alias has been deprecated. Use "--additional-properties" instead.`);
if (args.includes("-it")) errorAndExit(`The -it alias has been deprecated. Use "--immutable-types" instead.`);

const flags = parser(args, {
array: ["header"],
boolean: [
"help",
"version",
"defaultNonNullable",
"immutableTypes",
"contentNever",
Expand All @@ -57,7 +60,6 @@ const flags = parser(args, {
"pathParamsAsTypes",
"alphabetize",
],
number: ["version"],
string: ["auth", "header", "headersObject", "httpMethod"],
alias: {
header: ["x"],
Expand Down Expand Up @@ -131,33 +133,37 @@ async function generateSchema(pathToSpec) {
}

async function main() {
if (flags.help) {
if ("help" in flags) {
console.info(HELP);
process.exit(0);
}
const packageJSON = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8"));
if ("version" in flags) {
console.info(`v${packageJSON.version}`);
process.exit(0);
}

let output = flags.output ? OUTPUT_FILE : OUTPUT_STDOUT; // FILE or STDOUT
let outputFile = new URL(flags.output, CWD);
let outputDir = new URL(".", outputFile);

const pathToSpec = input;

if (output === OUTPUT_FILE) {
const packageJSON = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8"));
console.info(`✨ ${BOLD}openapi-typescript ${packageJSON.version}${RESET}`); // only log if we’re NOT writing to stdout
}

// handle remote schema, exit
if (HTTP_RE.test(pathToSpec)) {
const pathToSpec = flags._[0];

// handle stdin schema, exit
if (!pathToSpec) {
if (output !== "." && output === OUTPUT_FILE) fs.mkdirSync(outputDir, { recursive: true });
await generateSchema(pathToSpec);
await generateSchema(process.stdin);
return;
}

// handle stdin schema, exit
if (pathToSpec === "-") {
// handle remote schema, exit
if (HTTP_RE.test(pathToSpec)) {
if (output !== "." && output === OUTPUT_FILE) fs.mkdirSync(outputDir, { recursive: true });
await generateSchema(process.stdin);
await generateSchema(pathToSpec);
return;
}

Expand All @@ -167,12 +173,12 @@ async function main() {

// error: no matches for glob
if (inputSpecPaths.length === 0) {
errorAndExit(` Could not find any specs matching "${pathToSpec}". Please check that the path is correct.`);
errorAndExit(` Could not find any specs matching "${pathToSpec}". Please check that the path is correct.`);
}

// error: tried to glob output to single file
if (isGlob && output === OUTPUT_FILE && fs.existsSync(outputDir) && fs.lstatSync(outputDir).isFile()) {
errorAndExit(` Expected directory for --output if using glob patterns. Received "${flags.output}".`);
errorAndExit(` Expected directory for --output if using glob patterns. Received "${flags.output}".`);
}

// generate schema(s) in parallel
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "openapi-typescript",
"description": "Generate TypeScript types from Swagger OpenAPI specs",
"version": "5.4.0",
"version": "6.0.0",
"author": "drew@pow.rs",
"license": "MIT",
"bin": {
Expand Down Expand Up @@ -66,6 +66,7 @@
"eslint": "^8.26.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-prettier": "^4.2.1",
"execa": "^6.1.0",
"prettier": "^2.7.1",
"typescript": "^4.8.4",
"vitest": "^0.24.5"
Expand Down
65 changes: 65 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

41 changes: 41 additions & 0 deletions test/cli.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { execa } from "execa";
import fs from "node:fs";
import { URL } from "node:url";

const cwd = new URL("../", import.meta.url);
const cmd = "./bin/cli.js";

describe("CLI", () => {
describe("snapshots", () => {
test("GitHub API", async () => {
const expected = fs.readFileSync(new URL("./examples/github-api.ts", cwd), "utf8").trim();
const { stdout } = await execa(cmd, ["./test/fixtures/github-api.yaml"], { cwd });
expect(stdout).toBe(expected);
});
test("Stripe API", async () => {
const expected = fs.readFileSync(new URL("./examples/stripe-api.ts", cwd), "utf8").trim();
const { stdout } = await execa(cmd, ["./test/fixtures/stripe-api.yaml"], {
cwd,
});
expect(stdout).toBe(expected);
});
test("stdin", async () => {
const expected = fs.readFileSync(new URL("./examples/stripe-api.ts", cwd), "utf8").trim();
const input = fs.readFileSync(new URL("./test/fixtures/stripe-api.yaml", cwd));
const { stdout } = await execa(cmd, { input });
expect(stdout).toBe(expected);
});
});

describe("flags", () => {
test("--help", async () => {
const { stdout } = await execa(cmd, ["--help"], { cwd });
expect(stdout).toEqual(expect.stringMatching(/^Usage\n\s+\$ openapi-typescript \[input\] \[options\]/));
});

test("--version", async () => {
const { stdout } = await execa(cmd, ["--version"], { cwd });
expect(stdout).toEqual(expect.stringMatching(/^v[\d.]+(-.*)?$/));
});
});
});