Skip to content

feat: export schemas types at root level #1260

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

Closed
wants to merge 23 commits into from
Closed
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/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ _Thanks, [@psmyrdek](https://github.com/psmyrdek)!_
| `--support-array-length` | | `false` | Generate tuples using array `minItems` / `maxItems` |
| `--alphabetize` | | `false` | Sort types alphabetically |
| `--exclude-deprecated` | | `false` | Exclude deprecated fields from types |
| `--root-types` | | `false` | Export schemas types at root level |

### `--path-params-as-types`

Expand Down
12 changes: 0 additions & 12 deletions packages/openapi-fetch/examples/sveltekit/src/app.d.ts

This file was deleted.

16 changes: 3 additions & 13 deletions packages/openapi-typescript/bin/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ Options
--path-params-as-types (optional) Substitute path parameter names with their respective types
--alphabetize (optional) Sort types alphabetically
--exclude-deprecated (optional) Exclude deprecated fields from types
--root-types (optional) Export schemas types at root level
`;

const OUTPUT_FILE = "FILE";
Expand All @@ -44,19 +45,7 @@ if (args.includes("-it")) errorAndExit(`The -it alias has been deprecated. Use "

const flags = parser(args, {
array: ["header"],
boolean: [
"help",
"version",
"defaultNonNullable",
"emptyObjectsUnknown",
"immutableTypes",
"contentNever",
"exportType",
"supportArrayLength",
"pathParamsAsTypes",
"alphabetize",
"excludeDeprecated",
],
boolean: ["help", "version", "defaultNonNullable", "emptyObjectsUnknown", "immutableTypes", "contentNever", "exportType", "supportArrayLength", "pathParamsAsTypes", "alphabetize", "excludeDeprecated", "rootTypes"],
string: ["auth", "header", "headersObject", "httpMethod"],
alias: {
header: ["x"],
Expand Down Expand Up @@ -107,6 +96,7 @@ async function generateSchema(pathToSpec) {
pathParamsAsTypes: flags.pathParamsAsTypes,
alphabetize: flags.alphabetize,
excludeDeprecated: flags.excludeDeprecated,
rootTypes: flags.rootTypes,
});

// output
Expand Down
6 changes: 6 additions & 0 deletions packages/openapi-typescript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@
"name": "Drew Powers",
"email": "[email protected]"
},
"contributors": [
Copy link
Contributor

Choose a reason for hiding this comment

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

We’re not using this field in package.json. We’re tracking contributors via the docs site. Let’s remove it.

{
"name": "Jean Smaug",
"url": "https://maximeblanc.fr"
}
],
"license": "MIT",
"bin": {
"openapi-typescript": "bin/cli.js"
Expand Down
10 changes: 9 additions & 1 deletion packages/openapi-typescript/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import transformResponseObject from "./transform/response-object.js";
import transformSchemaObject from "./transform/schema-object.js";
import transformSchemaObjectMap from "./transform/schema-object-map.js";
import { error, escObjKey, getDefaultFetch, getEntries, getSchemaObjectComment, indent } from "./utils.js";

export * from "./types.js"; // expose all types to consumers

const EMPTY_OBJECT_RE = /^\s*\{?\s*\}?\s*$/;
Expand Down Expand Up @@ -55,6 +54,7 @@ async function openapiTS(schema: string | URL | OpenAPI3 | Readable, options: Op
silent: options.silent ?? false,
supportArrayLength: options.supportArrayLength ?? false,
excludeDeprecated: options.excludeDeprecated ?? false,
rootTypes: options.rootTypes ?? false,
};

// 1. load schema (and subschemas)
Expand Down Expand Up @@ -119,6 +119,14 @@ async function openapiTS(schema: string | URL | OpenAPI3 | Readable, options: Op

// 2c. root schema
const rootTypes = transformSchema(allSchemas["."].schema as OpenAPI3, ctx);
const typedComponents = (allSchemas["."].schema as OpenAPI3).components!;

if (options.rootTypes) {
for (const schema of Object.keys(typedComponents.schemas as object)) {
output.push(`export type ${schema} = external["."]["components"]["schemas"]["${schema}"];\n`);
}
}

for (const k of Object.keys(rootTypes)) {
if (rootTypes[k] && !EMPTY_OBJECT_RE.test(rootTypes[k])) {
output.push(options.exportType ? `export type ${k} = ${rootTypes[k]};` : `export interface ${k} ${rootTypes[k]}`, "");
Expand Down
3 changes: 3 additions & 0 deletions packages/openapi-typescript/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -648,6 +648,8 @@ export interface OpenAPITSOptions {
httpMethod?: string;
/** (optional) Export type instead of interface */
exportType?: boolean;
/** (optional) Generate schemas types at root level */
rootTypes?: boolean;
Copy link
Contributor

Choose a reason for hiding this comment

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

let’s also add this to the ctx object so it’s more explicitly passed around

/** (optional) Generate tuples using array minItems / maxItems */
supportArrayLength?: boolean;
/** (optional) Substitute path parameter names with their respective types */
Expand Down Expand Up @@ -709,6 +711,7 @@ export interface GlobalContext {
silent: boolean;
supportArrayLength: boolean;
excludeDeprecated: boolean;
rootTypes: boolean;
}

export type $defs = Record<string, SchemaObject>;
Expand Down
1 change: 1 addition & 0 deletions packages/openapi-typescript/test/components-object.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const options: GlobalContext = {
supportArrayLength: false,
transform: undefined,
excludeDeprecated: false,
rootTypes: false,
};

const basicSchema: ComponentsObject = {
Expand Down
1 change: 1 addition & 0 deletions packages/openapi-typescript/test/header-object.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const options: TransformHeaderObjectOptions = {
supportArrayLength: false,
transform: undefined,
excludeDeprecated: false,
rootTypes: false,
},
};

Expand Down
58 changes: 58 additions & 0 deletions packages/openapi-typescript/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1283,6 +1283,64 @@ export type $defs = Record<string, never>;

export type external = Record<string, never>;

export type operations = Record<string, never>;
`);
});
});

describe("rootTypes helpers", () => {
test("should be added only when used", async () => {
const generated = await openapiTS(
{
openapi: "3.1",
info: { title: "Test", version: "1.0" },
components: {
schemas: {
User: {
allOf: [
{
type: "object",
properties: { firstName: { type: "string" }, lastName: { type: "string" } },
},
{
type: "object",
properties: { middleName: { type: "string" } },
},
],
required: ["firstName", "lastName"],
},
},
},
},
{ rootTypes: true },
);
expect(generated).toBe(`${BOILERPLATE}${WITH_REQUIRED_TYPE_HELPERS}
export type User = external["."]["components"]["schemas"]["User"];

export type paths = Record<string, never>;

export type webhooks = Record<string, never>;

export interface components {
schemas: {
User: WithRequired<{
firstName?: string;
lastName?: string;
} & {
middleName?: string;
}, "firstName" | "lastName">;
};
responses: never;
parameters: never;
requestBodies: never;
headers: never;
pathItems: never;
}

export type $defs = Record<string, never>;

export type external = Record<string, never>;

export type operations = Record<string, never>;
`);
});
Expand Down
1 change: 1 addition & 0 deletions packages/openapi-typescript/test/load.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ async function load(schema: URL | Subschema | Readable, options?: Partial<LoadOp
supportArrayLength: false,
transform: undefined,
excludeDeprecated: false,
rootTypes: false,
...options,
});
}
1 change: 1 addition & 0 deletions packages/openapi-typescript/test/operation-object.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const ctx: GlobalContext = {
supportArrayLength: false,
transform: undefined,
excludeDeprecated: false,
rootTypes: false,
};

const options = { ctx, path: "#/paths/~get-item" };
Expand Down
1 change: 1 addition & 0 deletions packages/openapi-typescript/test/path-item-object.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const options: TransformPathItemObjectOptions = {
supportArrayLength: false,
transform: undefined,
excludeDeprecated: false,
rootTypes: false,
},
};

Expand Down
1 change: 1 addition & 0 deletions packages/openapi-typescript/test/paths-object.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const options: GlobalContext = {
supportArrayLength: false,
transform: undefined,
excludeDeprecated: false,
rootTypes: false,
};

describe("Paths Object", () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const options: TransformRequestBodyObjectOptions = {
supportArrayLength: false,
transform: undefined,
excludeDeprecated: false,
rootTypes: false,
},
};

Expand Down
1 change: 1 addition & 0 deletions packages/openapi-typescript/test/response-object.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const options: TransformResponseObjectOptions = {
supportArrayLength: false,
transform: undefined,
excludeDeprecated: false,
rootTypes: false,
},
};

Expand Down
1 change: 1 addition & 0 deletions packages/openapi-typescript/test/schema-object.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const options: TransformSchemaObjectOptions = {
supportArrayLength: false,
transform: undefined,
excludeDeprecated: false,
rootTypes: false,
},
};

Expand Down
1 change: 1 addition & 0 deletions packages/openapi-typescript/test/webhooks-object.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const options: GlobalContext = {
supportArrayLength: false,
transform: undefined,
excludeDeprecated: false,
rootTypes: false,
};

describe("Webhooks Object", () => {
Expand Down