Skip to content

Add support for x-enum-varnames and x-enum-descriptions #1374

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 2 commits into from
Oct 11, 2023
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
5 changes: 5 additions & 0 deletions .changeset/chilled-news-design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"openapi-typescript": major
Copy link
Contributor

@drwpow drwpow Oct 8, 2023

Choose a reason for hiding this comment

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

Suggested change
"openapi-typescript": major
"openapi-typescript": minor

Copy link
Contributor Author

Choose a reason for hiding this comment

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

done

---

Add support for x-enum-varnames and x-enum-descriptions
48 changes: 35 additions & 13 deletions packages/openapi-typescript/src/lib/ts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,8 @@ export function tsDedupe(types: ts.TypeNode[]): ts.TypeNode[] {
export function tsEnum(
name: string,
members: (string | number)[],
membersNames?: string[],
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
membersNames?: string[],
metadata?: { name?: string, description?: string }[],

I think this is an easier-to-use signature; I find the former where multiple ordered params have the same type to be easy to make mistakes in rearranging them.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Agree, done 👍

membersDescriptions?: string[],
options?: { readonly?: boolean; export?: boolean },
) {
let enumName = name.replace(JS_ENUM_INVALID_CHARS_RE, (c) => {
Expand All @@ -249,28 +251,48 @@ export function tsEnum(
})
: undefined,
/* name */ enumName,
/* members */ members.map(tsEnumMember),
/* members */ members.map((value, i) =>
tsEnumMember(value, membersNames?.[i], membersDescriptions?.[i]),
),
);
}

/** Sanitize TS enum member expression */
export function tsEnumMember(value: string | number) {
if (typeof value === "number") {
return ts.factory.createEnumMember(
`Value${String(value)}`.replace(".", "_"), // don’t forget decimals
ts.factory.createNumericLiteral(value),
);
}
let name = value;
export function tsEnumMember(
value: string | number,
memberName?: string,
description?: string,
) {
let name = memberName ?? String(value);
if (!JS_PROPERTY_INDEX_RE.test(name)) {
if (Number(name[0]) >= 0) {
name = `Value${name}`;
name = `Value${name}`.replace(".", "_"); // don't forged decimals;
}
name = name.replace(JS_PROPERTY_INDEX_INVALID_CHARS_RE, "_");
}
return ts.factory.createEnumMember(
name,
ts.factory.createStringLiteral(value),

let member;
if (typeof value === "number") {
member = ts.factory.createEnumMember(
name,
ts.factory.createNumericLiteral(value),
);
} else {
member = ts.factory.createEnumMember(
name,
ts.factory.createStringLiteral(value),
);
}

if (description == undefined) {
return member;
}

return ts.addSyntheticLeadingComment(
member,
ts.SyntaxKind.SingleLineCommentTrivia,
" ".concat(description.trim()),
true,
);
}

Expand Down
2 changes: 2 additions & 0 deletions packages/openapi-typescript/src/transform/schema-object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,8 @@ export function transformSchemaObjectWithComposition(
const enumType = tsEnum(
enumName,
schemaObject.enum as (string | number)[],
schemaObject["x-enum-varnames"],
schemaObject["x-enum-descriptions"],
{ export: true, readonly: options.ctx.immutable },
);
options.ctx.injectFooter.push(enumType);
Expand Down
71 changes: 71 additions & 0 deletions packages/openapi-typescript/test/lib/ts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,77 @@ describe("tsEnum", () => {
Value100 = 100,
Value101 = 101,
Value102 = 102
}`);
});

it("number members with x-enum-descriptions", () => {
expect(
astToString(
tsEnum(".Error.code.", [100, 101, 102], undefined, [
"Code 100",
"Code 101",
"Code 102",
]),
).trim(),
).toBe(`enum ErrorCode {
// Code 100
Value100 = 100,
// Code 101
Value101 = 101,
// Code 102
Value102 = 102
}`);
});

it("x-enum-varnames", () => {
expect(
astToString(
tsEnum(
".Error.code.",
[100, 101, 102],
["Unauthorized", "NotFound", "PermissionDenied"],
),
).trim(),
).toBe(`enum ErrorCode {
Unauthorized = 100,
NotFound = 101,
PermissionDenied = 102
}`);
});

it("x-enum-varnames with numeric prefix", () => {
expect(
astToString(
tsEnum(".Error.code.", [100, 101, 102], ["0a", "1b", "2c"]),
).trim(),
).toBe(`enum ErrorCode {
Value0a = 100,
Value1b = 101,
Value2c = 102
}`);
});

it("x-enum-descriptions with x-enum-varnames", () => {
expect(
astToString(
tsEnum(
".Error.code.",
[100, 101, 102],
["Unauthorized", "NotFound", "PermissionDenied"],
[
"User is unauthorized",
"Item not found",
"User doesn't have permissions",
],
),
).trim(),
).toBe(`enum ErrorCode {
// User is unauthorized
Unauthorized = 100,
// Item not found
NotFound = 101,
// User doesn't have permissions
PermissionDenied = 102
}`);
});
});
Expand Down