From ac4ce9b5a0ca9d0873f3c02aecaa96c4edbeed81 Mon Sep 17 00:00:00 2001 From: Michael Nahkies Date: Sat, 22 Apr 2023 13:58:54 +0100 Subject: [PATCH] fix: replace . in identifiers (#50) the stripe definitions include schema names like: ``` checkout.session ``` which isn't a valid identifier in typescript. replace these with `_` and add tests for the `openapi-utils.ts` functions should get https://github.com/mnahkies/openapi-code-generator/pull/49 closer to passing. --- .../src/core/openapi-utils.spec.ts | 34 +++++++++++++++++++ .../src/core/openapi-utils.ts | 4 +-- 2 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 packages/openapi-code-generator/src/core/openapi-utils.spec.ts diff --git a/packages/openapi-code-generator/src/core/openapi-utils.spec.ts b/packages/openapi-code-generator/src/core/openapi-utils.spec.ts new file mode 100644 index 00000000..b6cd236f --- /dev/null +++ b/packages/openapi-code-generator/src/core/openapi-utils.spec.ts @@ -0,0 +1,34 @@ +import {describe, expect} from "@jest/globals" +import {getNameFromRef, isRef} from "./openapi-utils" + +describe("core/openapi-utils", () => { + + describe("#isRef", () => { + + it("returns true if $ref is defined", () => { + expect(isRef({$ref: "#/something"})).toBe(true) + }) + + it("returns false if $ref is not defined", () => { + expect(isRef({type: "number"})).toBe(false) + }) + + }) + + describe("#getNameFromRef", () => { + + it("includes the given prefix", () => { + expect(getNameFromRef({$ref: "#/components/schemas/Foo"}, "t_")).toBe("t_Foo") + }) + + it("replaces - with _", () => { + expect(getNameFromRef({$ref: "#/components/schemas/Foo-Bar"}, "t_")).toBe("t_Foo_Bar") + }) + + it("replaces . with _", () => { + expect(getNameFromRef({$ref: "#/components/schemas/Foo.Bar"}, "t_")).toBe("t_Foo_Bar") + }) + + }) + +}) diff --git a/packages/openapi-code-generator/src/core/openapi-utils.ts b/packages/openapi-code-generator/src/core/openapi-utils.ts index 8661a3ac..b810572a 100644 --- a/packages/openapi-code-generator/src/core/openapi-utils.ts +++ b/packages/openapi-code-generator/src/core/openapi-utils.ts @@ -1,6 +1,6 @@ import {Reference} from "./openapi-types" -export function isRef(it: any | Reference): it is Reference { +export function isRef(it: unknown | Reference): it is Reference { if (!it || typeof it !== "object") { return false } @@ -16,5 +16,5 @@ export function getNameFromRef({$ref}: Reference, prefix: string): string { // TODO: this is a hack to workaround reserved words being used as names // can likely improve to selectively apply when a reserved word is used. - return prefix + name.replace(/-/g, "_") + return prefix + name.replace(/[-.]+/g, "_") }