Skip to content

Commit ebc7031

Browse files
committed
feat: 解析枚举值
1 parent d8c2d1e commit ebc7031

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

src/lib/parse-schema.ts

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,14 @@ export const parseSchema = (
99
const parsed = refToObject(docs, schema);
1010
const nullable = parsed.nullable ? ' | null' : '';
1111

12+
if (parsed.enum?.length) {
13+
return `${parsed.enum.map((item) => (typeof item === 'number' ? item : `"${item}"`)).join(' | ')}${nullable}`;
14+
}
15+
16+
if (parsed.oneOf) {
17+
return parsed.oneOf.map((schema) => parseSchema(docs, schema)).join(' | ');
18+
}
19+
1220
switch (parsed.type) {
1321
case 'array':
1422
return `(${parseSchema(docs, parsed.items)})[]${nullable}`;
@@ -29,9 +37,5 @@ export const parseSchema = (
2937
return `string${nullable}`;
3038
}
3139

32-
if (parsed.oneOf) {
33-
return parsed.oneOf.map((schema) => parseSchema(docs, schema)).join(' | ');
34-
}
35-
3640
return 'unknown';
3741
};

test/lib/parse-schema.test.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,12 @@ describe('常规', () => {
7575
});
7676
expect(type).toMatchInlineSnapshot(`"string | boolean | number"`);
7777
});
78+
79+
test('枚举', () => {
80+
expect(
81+
parseSchema(docs, { enum: ['foo', 'bar', 'baz', 1, 2] }),
82+
).toMatchInlineSnapshot(`""foo" | "bar" | "baz" | 1 | 2"`);
83+
});
7884
});
7985

8086
describe('nullable', () => {
@@ -128,6 +134,12 @@ describe('nullable', () => {
128134
parseSchema(docs, { type: 'string', format: 'binary', nullable: true }),
129135
).toMatchInlineSnapshot(`"Blob | null"`);
130136
});
137+
138+
test('枚举', () => {
139+
expect(
140+
parseSchema(docs, { enum: ['foo', 'bar', 'baz'], nullable: true }),
141+
).toMatchInlineSnapshot(`""foo" | "bar" | "baz" | null"`);
142+
});
131143
});
132144

133145
test('未知类型', () => {

0 commit comments

Comments
 (0)