Skip to content

Update examples, update validator recommendation #1113

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
May 15, 2023
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
1 change: 1 addition & 0 deletions docs/src/content/docs/about.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ description: Additional info about this project
## Project goals

1. Support converting any valid OpenAPI schema to TypeScript types, no matter how complicated.
1. Generate **runtime-free types** for maximum performance.
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤔 Wondering if there’s a better way to say this. Only lately realized that there is an entire school of thought that believes codegen is a natural pair to OpenAPI and I strongly disagree. After all, why impose heavy runtime SDKs on things that don’t need it? TypeScript has the superpower of static inference that can deliver all the resiliency of static typing but without any runtime impact. In a sense, codegen feels antithetical to how TypeScript works itself.

Anyway, there are probably better terms to express this sentiment, but just putting this placeholder idea here for now.

1. This library does **NOT** validate your schema, there are other libraries for that.
1. The generated TypeScript types **must** match your schema as closely as possible (e.g. no renaming to `PascalCase`)
1. This library should never require Java, node-gyp, or some other complex environment to work. This should require Node.js and nothing else.
Expand Down
9 changes: 4 additions & 5 deletions docs/src/content/docs/introduction.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,9 @@ The code is <a href="https://github.com/drwpow/openapi-typescript/blob/main/pack
## Features

- ✅ Supports OpenAPI 3.0 and 3.1 (including advanced features like <a href="https://spec.openapis.org/oas/v3.1.0#discriminator-object" target="_blank" rel="noopener noreferrer">discriminators</a>)
- ✅ Supports YAML and JSON
- ✅ Supports loading via remote URL (simple authentication supported with the `--auth` flag)
- ✅ Supports remote references: `$ref: "external.yaml#components/schemas/User"`
- ✅ Fetches remote schemas quickly using <a href="https://www.npmjs.com/package/undici" target="_blank" rel="noopener noreferrer">undici</a>
- ✅ Generate **runtime-free types** that outperform old-school codegen
- ✅ Load schemas from YAML or JSON, locally or remotely
- ✅ Native Node.js code is fast and generates types within milliseconds

_Note: OpenAPI 2.x is supported with versions `5.x` and previous_

Expand Down Expand Up @@ -45,7 +44,7 @@ npx openapi-typescript https://myapi.dev/api/v1/openapi.yaml -o ./path/to/my/sch
# 🚀 https://myapi.dev/api/v1/openapi.yaml -> ./path/to/my/schema.d.ts [250ms]
```

> ⚠️ Be sure to <a href="(https://apitools.dev/swagger-cli/" target="_blank" rel="noopener noreferrer">validate your schemas</a>! openapi-typescript will err on invalid schemas.
> ⚠️ Be sure to <a href="https://redocly.com/docs/cli/commands/lint/" target="_blank" rel="noopener noreferrer">validate your schemas</a>! openapi-typescript will err on invalid schemas.

Then, import schemas from the generated file like so:

Expand Down
2 changes: 1 addition & 1 deletion docs/src/content/docs/openapi-fetch/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ Next, generate TypeScript types from your OpenAPI schema using openapi-typescrip
npx openapi-typescript ./path/to/api/v1.yaml -o ./src/lib/api/v1.d.ts
```

> ⚠️ Be sure to <a href="(https://apitools.dev/swagger-cli/" target="_blank" rel="noopener noreferrer">validate your schemas</a>! openapi-typescript will err on invalid schemas.
> ⚠️ Be sure to <a href="https://redocly.com/docs/cli/commands/lint/" target="_blank" rel="noopener noreferrer">validate your schemas</a>! openapi-typescript will err on invalid schemas.

Lastly, be sure to **run typechecking** in your project. This can be done by adding `tsc --noEmit` to your <a href="https://docs.npmjs.com/cli/v9/using-npm/scripts" target="_blank" rel="noopener noreferrer">npm scripts</a> like so:

Expand Down
2 changes: 1 addition & 1 deletion packages/openapi-fetch/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ Next, generate TypeScript types from your OpenAPI schema using openapi-typescrip
npx openapi-typescript ./path/to/api/v1.yaml -o ./src/lib/api/v1.d.ts
```

> ⚠️ Be sure to <a href="(https://apitools.dev/swagger-cli/" target="_blank" rel="noopener noreferrer">validate your schemas</a>! openapi-typescript will err on invalid schemas.
> ⚠️ Be sure to <a href="https://redocly.com/docs/cli/commands/lint/" target="_blank" rel="noopener noreferrer">validate your schemas</a>! openapi-typescript will err on invalid schemas.

Lastly, be sure to **run typechecking** in your project. This can be done by adding `tsc --noEmit` to your <a href="https://docs.npmjs.com/cli/v9/using-npm/scripts" target="_blank" rel="noopener noreferrer">npm scripts</a> like so:

Expand Down
66 changes: 30 additions & 36 deletions packages/openapi-typescript/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,31 +6,48 @@ The code is [MIT-licensed](./LICENSE) and free for use.

**Features**

- ✅ Supports YAML and JSON formats
- ✅ Supports advanced OpenAPI 3.1 features like [discriminators](https://spec.openapis.org/oas/v3.1.0#discriminator-object)
- ✅ Supports loading via remote URL (simple authentication supported with the `--auth` flag)
- ✅ Supports remote references: `$ref: "external.yaml#components/schemas/User"`
- ✅ Fetches remote schemas quickly using [undici](https://www.npmjs.com/package/undici)
- ✅ Supports OpenAPI 3.0 and 3.1 (including advanced features like <a href="https://spec.openapis.org/oas/v3.1.0#discriminator-object" target="_blank" rel="noopener noreferrer">discriminators</a>)
- ✅ Generate **runtime-free types** that outperform old-school codegen
- ✅ Load schemas from YAML or JSON, locally or remotely
- ✅ Native Node.js code is fast and generates types within milliseconds

**Examples**

👀 [See examples](./examples/)

## Usage

Note:️ openapiTS requires **VALID** OpenAPI 3.x schemas to work, and this library does not handle validation. There are several quality tools that handle this like [@apidevtools/swagger-parser](https://www.npmjs.com/package/@apidevtools/swagger-parser). Make sure to validate your schemas first!
First, generate a local type file by running `npx openapi-typescript`:

### 🖥️ CLI
```bash
# Local schema
npx openapi-typescript ./path/to/my/schema.yaml -o ./path/to/my/schema.d.ts
# 🚀 ./path/to/my/schema.yaml -> ./path/to/my/schema.d.ts [7ms]

#### 🗄️ Reading schemas
# Remote schema
npx openapi-typescript https://myapi.dev/api/v1/openapi.yaml -o ./path/to/my/schema.d.ts
# 🚀 https://myapi.dev/api/v1/openapi.yaml -> ./path/to/my/schema.d.ts [250ms]
```

```bash
npx openapi-typescript schema.yaml --output schema.ts
> ⚠️ Be sure to <a href="https://redocly.com/docs/cli/commands/lint/" target="_blank" rel="noopener noreferrer">validate your schemas</a>! openapi-typescript will err on invalid schemas.

Then, import schemas from the generated file like so:

```ts
import { paths, components } from "./path/to/my/schema"; // <- generated by openapi-typescript

# 🚀 schema.yaml -> schema.ts [7ms]
// Schema Obj
type MyType = components["schemas"]["MyType"];

// Path params
type EndpointParams = paths["/my/endpoint"]["parameters"];

// Response obj
type SuccessResponse = paths["/my/endpoint"]["get"]["responses"][200]["content"]["application/json"]["schema"];
type ErrorResponse = paths["/my/endpoint"]["get"]["responses"][500]["content"]["application/json"]["schema"];
```

##### 🦠 Globbing local schemas
#### 🦠 Globbing local schemas

```bash
npx openapi-typescript "specs/**/*.yaml" --output schemas/
Expand All @@ -52,30 +69,6 @@ npx openapi-typescript https://petstore3.swagger.io/api/v3/openapi.yaml --output

_Thanks, [@psmyrdek](https://github.com/psmyrdek)!_

#### 🟦 Using in TypeScript

Import any top-level item from the generated spec to use it. It works best if you also alias types to save on typing:

```ts
import { components } from "./generated-schema.ts";

type APIResponse = components["schemas"]["APIResponse"];
```

Because OpenAPI schemas may have invalid TypeScript characters as names, the square brackets are a safe way to access every property.

##### 🏗️ Operations

Operations can be imported directly by their [operationId](https://spec.openapis.org/oas/latest.html#operation-object):

```ts
import { operations } from "./generated-schema.ts";

type getUsersById = operations["getUsersById"];
```

_Thanks, [@gr2m](https://github.com/gr2m)!_

#### ⚾ Fetching data

Fetching data can be done simply and safely using an **automatically-typed fetch wrapper**:
Expand Down Expand Up @@ -268,6 +261,7 @@ There are many other uses for this besides checking `format`. Because this must
## 🏅 Project Goals

1. Support converting any valid OpenAPI schema to TypeScript types, no matter how complicated.
1. Generate **runtime-free types** for maximum performance.
1. This library does **NOT** validate your schema, there are other libraries for that.
1. The generated TypeScript types **must** match your schema as closely as possible (e.g. no renaming to `PascalCase`)
1. This library should never require Java, node-gyp, or some other complex environment to work. This should require Node.js and nothing else.
Expand Down
28 changes: 27 additions & 1 deletion packages/openapi-typescript/examples/digital-ocean-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6162,7 +6162,33 @@ export interface external {
redis_acl_channels_default?: "allchannels" | "resetchannels";
}
"resources/databases/models/source_database.yml": {
source?: external["resources/databases/models/database_connection.yml"];
source?: {
/**
* @description The FQDN pointing to the database cluster's current primary node.
* @example backend-do-user-19081923-0.db.ondigitalocean.com
*/
host?: string;
/**
* @description The port on which the database cluster is listening.
* @example 25060
*/
port?: number;
/**
* @description The name of the default database.
* @example defaultdb
*/
dbname?: string;
/**
* @description The default user for the database.
* @example doadmin
*/
username?: string;
/**
* @description The randomly generated password for the default user.
* @example wv78n3zpz42xezdk
*/
password?: string;
};
/**
* @description Enables SSL encryption when connecting to the source database.
* @example false
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
lang: cURL
source: |-
curl -X PUT \
curl -X GET \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $DIGITALOCEAN_TOKEN" \
-d '{"source":{"host":"source-do-user-6607903-0.b.db.ondigitalocean.com","dbname":"defaultdb","port":25060,"username":"doadmin","password":"paakjnfe10rsrsmf"},"disable_ssl":false}' \
"https://api.digitalocean.com/v2/databases/9cc10173-e9ea-4176-9dbc-a4cee4c4ff30/online-migration"
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,28 @@ type: object

properties:
source:
allOf:
- $ref: './database_connection.yml'
type: object
properties:
host:
type: string
description: The FQDN pointing to the database cluster's current primary node.
example: backend-do-user-19081923-0.db.ondigitalocean.com
port:
type: integer
description: The port on which the database cluster is listening.
example: 25060
dbname:
type: string
description: The name of the default database.
example: defaultdb
username:
type: string
description: The default user for the database.
example: doadmin
password:
type: string
description: The randomly generated password for the default user.
example: wv78n3zpz42xezdk
disable_ssl:
type: boolean
description: Enables SSL encryption when connecting to the source database.
Expand Down
Loading