Skip to content

fix(openapi-typescript): Stringify primitive constant values #1149

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
Jun 12, 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
5 changes: 5 additions & 0 deletions .changeset/eighty-chairs-join.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"openapi-typescript": minor
---

Stringify const values with no specified type
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,7 @@ export function defaultSchemaObjectTransform(schemaObject: SchemaObject | Refere

// const (valid for any type)
if (schemaObject.const !== null && schemaObject.const !== undefined) {
let schemaConst = schemaObject.const as any;
if ("type" in schemaObject) {
if (schemaObject.type === "string") {
schemaConst = escStr(schemaConst);
}
}
return transformSchemaObject(schemaConst, {
return transformSchemaObject(escStr(schemaObject.const) as any, {
path,
ctx: { ...ctx, immutableTypes: false, indentLv: indentLv + 1 }, // note: guarantee readonly happens once, here
});
Expand Down
2 changes: 1 addition & 1 deletion packages/openapi-typescript/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ export function tsUnionOf(...types: (string | number | boolean)[]): string {

/** escape string value */
export function escStr(input: any): string {
if (typeof input !== "string") return input;
if (typeof input !== "string") return JSON.stringify(input);
return `"${input.trim().replace(DOUBLE_QUOTE_RE, '\\"')}"`;
}

Expand Down
15 changes: 15 additions & 0 deletions packages/openapi-typescript/test/schema-object.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,21 @@ describe("Schema Object", () => {
const generated = transformSchemaObject({ type: "string", const: "duck" }, options);
expect(generated).toBe(`"duck"`);
});

test("number", () => {
const generated = transformSchemaObject({ type: "number", const: 42 }, options);
expect(generated).toBe("42");
});

test("string, no type specified", () => {
const generated = transformSchemaObject({ const: "99" }, options);
expect(generated).toBe(`"99"`);
});

test("number, no type specified", () => {
const generated = transformSchemaObject({ const: 300 }, options);
expect(generated).toBe("300");
});
});

describe("polymorphic", () => {
Expand Down