Skip to content

Add a flag to skip Schema prefix when rendering root types #1958

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 7 commits into from
Nov 27, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
44 changes: 25 additions & 19 deletions packages/openapi-typescript/bin/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,26 +11,27 @@ const HELP = `Usage
$ openapi-typescript [input] [options]

Options
--help Display this
--version Display the version
--redocly [path], -c Specify path to Redocly config (default: redocly.yaml)
--output, -o Specify output file (if not specified in redocly.yaml)
--enum Export true TS enums instead of unions
--enum-values Export enum values as arrays
--dedupe-enums Dedupe enum types when \`--enum=true\` is set
--check Check that the generated types are up-to-date. (default: false)
--export-type, -t Export top-level \`type\` instead of \`interface\`
--immutable Generate readonly types
--additional-properties Treat schema objects as if \`additionalProperties: true\` is set
--empty-objects-unknown Generate \`unknown\` instead of \`Record<string, never>\` for empty objects
--default-non-nullable Set to \`false\` to ignore default values when generating non-nullable types
--help Display this
--version Display the version
--redocly [path], -c Specify path to Redocly config (default: redocly.yaml)
--output, -o Specify output file (if not specified in redocly.yaml)
--enum Export true TS enums instead of unions
--enum-values Export enum values as arrays
--dedupe-enums Dedupe enum types when \`--enum=true\` is set
--check Check that the generated types are up-to-date. (default: false)
--export-type, -t Export top-level \`type\` instead of \`interface\`
--immutable Generate readonly types
--additional-properties Treat schema objects as if \`additionalProperties: true\` is set
--empty-objects-unknown Generate \`unknown\` instead of \`Record<string, never>\` for empty objects
--default-non-nullable Set to \`false\` to ignore default values when generating non-nullable types
--properties-required-by-default
Treat schema objects as if \`required\` is set to all properties by default
--array-length Generate tuples using array minItems / maxItems
--path-params-as-types Convert paths to template literal types
--alphabetize Sort object keys alphabetically
--exclude-deprecated Exclude deprecated types
--root-types (optional) Export schemas types at root level
Treat schema objects as if \`required\` is set to all properties by default
--array-length Generate tuples using array minItems / maxItems
--path-params-as-types Convert paths to template literal types
--alphabetize Sort object keys alphabetically
--exclude-deprecated Exclude deprecated types
--root-types (optional) Export schemas types at root level
--root-types-no-schema-prefix (optional) Do not add "Schema" prefix to types at the root level (should be used with --root-types)
`;

const OUTPUT_FILE = "FILE";
Expand All @@ -56,6 +57,9 @@ if (args.includes("-it")) {
if (args.includes("--redoc")) {
errorAndExit(`The --redoc config flag has been renamed to "--redocly" (or -c as shorthand).`);
}
if (args.includes("--root-types-no-schema-prefix") && !args.includes("--root-types")) {
console.warn("--root-types-no-schema-prefix has no effect without --root-types flag");
}

const flags = parser(args, {
boolean: [
Expand All @@ -76,6 +80,7 @@ const flags = parser(args, {
"immutable",
"pathParamsAsTypes",
"rootTypes",
"rootTypesNoSchemaPrefix",
],
string: ["output", "redocly"],
alias: {
Expand Down Expand Up @@ -136,6 +141,7 @@ async function generateSchema(schema, { redocly, silent = false }) {
immutable: flags.immutable,
pathParamsAsTypes: flags.pathParamsAsTypes,
rootTypes: flags.rootTypes,
rootTypesNoSchemaPrefix: flags.rootTypesNoSchemaPrefix,
redocly,
silent,
}),
Expand Down
1 change: 1 addition & 0 deletions packages/openapi-typescript/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ export default async function openapiTS(
exportType: options.exportType ?? false,
immutable: options.immutable ?? false,
rootTypes: options.rootTypes ?? false,
rootTypesNoSchemaPrefix: options.rootTypesNoSchemaPrefix ?? false,
injectFooter: [],
pathParamsAsTypes: options.pathParamsAsTypes ?? false,
postTransform: typeof options.postTransform === "function" ? options.postTransform : undefined,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,15 @@ export default function transformComponentsObject(componentsObject: ComponentsOb
let aliasName = changeCase.pascalCase(singularizeComponentKey(key)) + changeCase.pascalCase(name);
// Add counter suffix (e.g. "_2") if conflict in name
let conflictCounter = 1;

let rootTypePrefix = changeCase.pascalCase(singularizeComponentKey(key));
if (ctx.rootTypesNoSchemaPrefix && key.toLowerCase() == "schemas") {
rootTypePrefix = "";
}

while (rootTypeAliases[aliasName] !== undefined) {
conflictCounter++;
aliasName = `${changeCase.pascalCase(singularizeComponentKey(key))}${changeCase.pascalCase(name)}_${conflictCounter}`;
aliasName = `${rootTypePrefix}${changeCase.pascalCase(name)}_${conflictCounter}`;
}
const ref = ts.factory.createTypeReferenceNode(`components['${key}']['${name}']`);
const typeAlias = ts.factory.createTypeAliasDeclaration(
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 @@ -659,6 +659,8 @@ export interface OpenAPITSOptions {
propertiesRequiredByDefault?: boolean;
/** (optional) Generate schema types at root level */
rootTypes?: boolean;
/** (optional) Do not add Schema prefix to types at root level */
rootTypesNoSchemaPrefix?: boolean;
/**
* Configure Redocly for validation, schema fetching, and bundling
* @see https://redocly.com/docs/cli/configuration/
Expand Down Expand Up @@ -691,6 +693,7 @@ export interface GlobalContext {
postTransform: OpenAPITSOptions["postTransform"];
propertiesRequiredByDefault: boolean;
rootTypes: boolean;
rootTypesNoSchemaPrefix: boolean;
redoc: RedoclyConfig;
silent: boolean;
transform: OpenAPITSOptions["transform"];
Expand Down
Loading