Skip to content

Commit

Permalink
feat: ref 路径解析
Browse files Browse the repository at this point in the history
  • Loading branch information
cloudcome committed Apr 14, 2023
1 parent bbcad7f commit 9ecd29f
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/utils/string.ts
Original file line number Diff line number Diff line change
@@ -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),
};
}
27 changes: 27 additions & 0 deletions test/utils/string.test.ts
Original file line number Diff line number Diff line change
@@ -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<RefInfo>({
type: 'T',
props: [],
});
expect(refToTypeName('#/components/schemas/T/oo')).toEqual<RefInfo>({
type: 'T',
props: ['oo'],
});
expect(refToTypeName('#/components/schemas/T/oo/pp/qq')).toEqual<RefInfo>({
type: 'T',
props: ['oo', 'pp', 'qq'],
});
});

0 comments on commit 9ecd29f

Please sign in to comment.