From 9ecd29f8874526bade70363abbbc84d19ee8d06e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=23=E4=BA=91=E6=B7=A1=E7=84=B6?= Date: Fri, 14 Apr 2023 14:39:23 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20ref=20=E8=B7=AF=E5=BE=84=E8=A7=A3?= =?UTF-8?q?=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/utils/string.ts | 25 +++++++++++++++++++++++++ test/utils/string.test.ts | 27 +++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 src/utils/string.ts create mode 100644 test/utils/string.test.ts diff --git a/src/utils/string.ts b/src/utils/string.ts new file mode 100644 index 0000000..4aeeb49 --- /dev/null +++ b/src/utils/string.ts @@ -0,0 +1,25 @@ +export function buildName(origin: string, bigger = false) { + const name = + origin + .replace(/\W/g, '_') + .replace(/(^_+|_+$)/g, '') + .replace(/_(.)/g, ($0, $1: string) => $1.toUpperCase()) + .replace(/^\d+/, '') || 'unnamed'; + + return (bigger ? name[0].toUpperCase() : name[0].toLowerCase()) + name.slice(1); +} + +export interface RefInfo { + type: string; + props: string[]; +} + +export function refToTypeName(ref: string): RefInfo { + // #/components/schemas/{type}/{...prop} + const segs = ref.split('/').slice(3); + + return { + type: segs.at(0)!, + props: segs.slice(1), + }; +} diff --git a/test/utils/string.test.ts b/test/utils/string.test.ts new file mode 100644 index 0000000..a192b4f --- /dev/null +++ b/test/utils/string.test.ts @@ -0,0 +1,27 @@ +import { buildName, RefInfo, refToTypeName } from '../../src/utils/string'; + +test('buildName', () => { + expect(buildName('!')).toEqual('untitled'); + expect(buildName('??')).toEqual('untitled'); + expect(buildName('hello-world')).toEqual('helloWorld'); + expect(buildName('hello-world123')).toEqual('helloWorld123'); + expect(buildName('123hello-world123')).toEqual('helloWorld123'); + expect(buildName('123hello-world123')).toEqual('helloWorld123'); + expect(buildName('[[[123hello-world123]]]')).toEqual('helloWorld123'); + expect(buildName('[[[123hello-world123]]]', true)).toEqual('HelloWorld123'); +}); + +test('refToTypeName', () => { + expect(refToTypeName('#/components/schemas/T')).toEqual({ + type: 'T', + props: [], + }); + expect(refToTypeName('#/components/schemas/T/oo')).toEqual({ + type: 'T', + props: ['oo'], + }); + expect(refToTypeName('#/components/schemas/T/oo/pp/qq')).toEqual({ + type: 'T', + props: ['oo', 'pp', 'qq'], + }); +});