Skip to content

Commit 826d6ec

Browse files
committed
Refactor
1 parent b2ddda8 commit 826d6ec

File tree

195 files changed

+58979
-887505
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

195 files changed

+58979
-887505
lines changed

.gitignore

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,5 @@
1-
.dccache
2-
.cache
31
.DS_Store
4-
.idea/
5-
.nyc_output/
6-
**/generated/
7-
**/__snapshots__/
2+
test/fixtures/*.yaml
83
coverage/
94
dist
105
node_modules
11-
yarn.lock
12-
yarn-error.log

.npmrc

Lines changed: 0 additions & 1 deletion
This file was deleted.

README.md

Lines changed: 88 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ npx openapi-typescript "specs/**/*.yaml" --output schemas/
4545

4646
_Note: if generating a single schema, `--output` must be a file (preferably `*.ts`). If using globs, `--output` must be a directory._
4747

48-
_Thanks to [@sharmarajdaksh](https://github.com/sharmarajdaksh) for the glob feature!_
48+
_Thanks, [@sharmarajdaksh](https://github.com/sharmarajdaksh)!_
4949

5050
#### ☁️ Reading specs from remote resource
5151

@@ -56,7 +56,7 @@ npx openapi-typescript https://petstore3.swagger.io/api/v3/openapi.yaml --output
5656
# 🚀 https://petstore3.swagger.io/api/v3/openapi.yaml -> petstore.d.ts [650ms]
5757
```
5858

59-
_Thanks to [@psmyrdek](https://github.com/psmyrdek) for the remote spec feature!_
59+
_Thanks, [@psmyrdek](https://github.com/psmyrdek)!_
6060

6161
#### Using in TypeScript
6262

@@ -80,7 +80,7 @@ import { operations } from "./generated-schema.ts";
8080
type getUsersById = operations["getUsersById"];
8181
```
8282

83-
_Thanks to [@gr2m](https://github.com/gr2m) for the operations feature!_
83+
_Thanks, [@gr2m](https://github.com/gr2m)!_
8484

8585
#### openapi-typescript-fetch
8686

@@ -132,31 +132,96 @@ try {
132132

133133
#### Outputting to stdout
134134

135-
Simply omit the `--output` flag to return to stdout:
135+
Omit the `--output` flag to return to stdout:
136136

137137
```bash
138138
npx openapi-typescript schema.yaml
139139
```
140140

141-
#### CLI Options
142-
143-
| Option | Alias | Default | Description |
144-
| :----------------------------- | :---- | :------: | :-------------------------------------------------------------------------------------------------------------------------------------- |
145-
| `--output [location]` | `-o` | (stdout) | Where should the output file be saved? |
146-
| `--auth [token]` | | | (optional) Provide an auth token to be passed along in the request (only if accessing a private schema) |
147-
| `--header` | `-x` | | (optional) Provide an array of or singular headers as an alternative to a JSON object. Each header must follow the `key: value` pattern |
148-
| `--headersObject` | `-h` | | (optional) Provide a JSON object as string of HTTP headers for remote schema request. This will take priority over `--header` |
149-
| `--httpMethod` | `-m` | `GET` | (optional) Provide the HTTP Verb/Method for fetching a schema from a remote URL |
150-
| `--immutable-types` | `-it` | `false` | (optional) Generates immutable types (readonly properties and readonly array) |
151-
| `--additional-properties` | `-ap` | `false` | (optional) Allow arbitrary properties for all schema objects without `additionalProperties: false` |
152-
| `--default-non-nullable` | | `false` | (optional) Treat schema objects with default values as non-nullable |
153-
| `--prettier-config [location]` | `-c` | | (optional) Path to your custom Prettier configuration for output |
154-
| `--export-type` | | `false` | (optional) Export `type` instead of `interface` |
155-
| `--support-array-length` | | `false` | (optional) Generate tuples using array minItems / maxItems |
156-
| `--make-paths-enum` | `-pe` | `false` | (optional) Generate an enum of endpoint paths |
157-
| `--path-params-as-types` | | `false` | (optional) Substitute path parameter names with their respective types |
158-
| `--alphabetize` | | `false` | (optional) Sort types alphabetically |
159-
| `--raw-schema` | | `false` | Generate TS types from partial schema (e.g. having `components.schema` at the top level) |
141+
### Options
142+
143+
The following flags can be appended to the CLI command.
144+
145+
| Option | Alias | Default | Description |
146+
| :----------------------------- | :---- | :------: | :--------------------------------------------------------------------------------------------------------------------------- |
147+
| `--output [location]` | `-o` | (stdout) | Where should the output file be saved? |
148+
| `--auth [token]` | | | Provide an auth token to be passed along in the request (only if accessing a private schema) |
149+
| `--header` | `-x` | | Provide an array of or singular headers as an alternative to a JSON object. Each header must follow the `key: value` pattern |
150+
| `--headersObject` | `-h` | | Provide a JSON object as string of HTTP headers for remote schema request. This will take priority over `--header` |
151+
| `--httpMethod` | `-m` | `GET` | Provide the HTTP Verb/Method for fetching a schema from a remote URL |
152+
| `--immutable-types` | | `false` | Generates immutable types (readonly properties and readonly array) |
153+
| `--additional-properties` | | `false` | Allow arbitrary properties for all schema objects without `additionalProperties: false` |
154+
| `--default-non-nullable` | | `false` | Treat schema objects with default values as non-nullable |
155+
| `--export-type` | `-t` | `false` | Export `type` instead of `interface` |
156+
| `--path-params-as-types` | | `false` | Allow dynamic string lookups on the `paths` object |
157+
| `--support-array-length` | | `false` | Generate tuples using array `minItems` / `maxItems` |
158+
| `--alphabetize` | | `false` | Sort types alphabetically |
159+
160+
#### `--path-params-as-types`
161+
162+
By default, your URLs are preserved exactly as-written in your schema:
163+
164+
```ts
165+
export interface paths {
166+
'/user/{user_id}': components["schemas"]["User"];
167+
}
168+
```
169+
170+
Which means your type lookups also have to match the exact URL:
171+
172+
```ts
173+
import { paths } from './my-schema';
174+
175+
const url = `/user/${id}`;
176+
type UserResponses = paths['/user/{user_id}']['responses'];
177+
```
178+
179+
But when `--path-params-as-types` is enabled, you can take advantage of dynamic lookups like so:
180+
181+
```ts
182+
import { paths } from './my-schema';
183+
184+
const url = `/user/${id}`;
185+
type UserResponses = paths[url]['responses']; // automatically matches `paths['/user/{user_id}']`
186+
```
187+
188+
Though this is a contrived example, you could use this feature to automatically infer typing based on the URL in a fetch client or in some other useful place in your application.
189+
190+
_Thanks, [@Powell-v2](https://github.com/Powell-v2)!_
191+
192+
#### `--support-array-length`
193+
194+
This option is useful for generating tuples if an array type specifies `minItems` or `maxItems`.
195+
196+
For example, given the following schema:
197+
198+
```yaml
199+
components:
200+
schemas:
201+
TupleType
202+
type: array
203+
items:
204+
type: string
205+
minItems: 1
206+
maxItems: 2
207+
```
208+
209+
Enabling `--support-array-length` would change the typing like so:
210+
211+
```diff
212+
export interface components {
213+
schemas: {
214+
- TupleType: string[];
215+
+ TupleType: [string] | [string, string];
216+
};
217+
}
218+
```
219+
220+
This results in more explicit typechecking of array lengths.
221+
222+
_Note: this has a reasonable limit, so for example `maxItems: 100` would simply flatten back down to `string[];`_
223+
224+
_Thanks, [@kgtkr](https://github.com/kgtkr)!_
160225

161226
### 🐢 Node
162227

bin/cli.js

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ Options
2424
--content-never (optional) If supplied, an omitted reponse \`content\` property will be generated as \`never\` instead of \`unknown\`
2525
--additional-properties, -ap (optional) Allow arbitrary properties for all schema objects without "additionalProperties: false"
2626
--default-non-nullable (optional) If a schema object has a default value set, don’t mark it as nullable
27-
--prettier-config, -c (optional) specify path to Prettier config file
2827
--raw-schema (optional) Parse as partial schema (raw components)
2928
--paths-enum, -pe (optional) Generate an enum containing all API paths.
3029
--export-type (optional) Export type instead of interface
@@ -38,6 +37,7 @@ const OUTPUT_FILE = "FILE";
3837
const OUTPUT_STDOUT = "STDOUT";
3938
const CWD = new URL(`file://${process.cwd()}/`);
4039
const EXT_RE = /\.[^.]+$/i;
40+
const HTTP_RE = /^https?:\/\//;
4141

4242
const timeStart = process.hrtime();
4343

@@ -53,24 +53,20 @@ const flags = parser(args, {
5353
"defaultNonNullable",
5454
"immutableTypes",
5555
"contentNever",
56-
"rawSchema",
5756
"exportType",
5857
"supportArrayLength",
59-
"makePathsEnum",
6058
"pathParamsAsTypes",
6159
"alphabetize",
6260
],
6361
number: ["version"],
64-
string: ["auth", "header", "headersObject", "httpMethod", "prettierConfig"],
62+
string: ["auth", "header", "headersObject", "httpMethod"],
6563
alias: {
6664
additionalProperties: ["ap"],
6765
header: ["x"],
6866
headersObject: ["h"],
6967
httpMethod: ["m"],
7068
immutableTypes: ["it"],
7169
output: ["o"],
72-
prettierConfig: ["c"],
73-
makePathsEnum: ["pe"],
7470
},
7571
default: {
7672
httpMethod: "GET",
@@ -103,9 +99,6 @@ async function generateSchema(pathToSpec) {
10399
auth: flags.auth,
104100
defaultNonNullable: flags.defaultNonNullable,
105101
immutableTypes: flags.immutableTypes,
106-
prettierConfig: flags.prettierConfig,
107-
rawSchema: flags.rawSchema,
108-
makePathsEnum: flags.makePathsEnum,
109102
contentNever: flags.contentNever,
110103
silent: output === OUTPUT_STDOUT,
111104
version: flags.version,
@@ -156,13 +149,8 @@ async function main() {
156149
console.info(`✨ ${BOLD}openapi-typescript ${packageJSON.version}${RESET}`); // only log if we’re NOT writing to stdout
157150
}
158151

159-
// error: --raw-schema
160-
if (flags.rawSchema && !flags.version) {
161-
throw new Error(`--raw-schema requires --version flag`);
162-
}
163-
164152
// handle remote schema, exit
165-
if (/^https?:\/\//.test(pathToSpec)) {
153+
if (HTTP_RE.test(pathToSpec)) {
166154
if (output !== "." && output === OUTPUT_FILE) fs.mkdirSync(outputDir, { recursive: true });
167155
await generateSchema(pathToSpec);
168156
return;

0 commit comments

Comments
 (0)