improve parseTypeBox utils: support enum and union

This commit is contained in:
Yanzhen Yu 2021-11-15 16:41:10 +08:00
parent 942523da42
commit 51248a9b6c
2 changed files with 56 additions and 10 deletions

View File

@ -21,4 +21,44 @@ describe('parseTypeBox function', () => {
});
expect(parseTypeBox(type)).toMatchObject({ key: '', value: [] });
});
it('can parse enum', () => {
expect(
parseTypeBox(
Type.KeyOf(
Type.Object({
foo: Type.String(),
bar: Type.String(),
})
)
)
).toEqual('foo');
});
it('can parse anyOf', () => {
expect(
parseTypeBox(
Type.Union([
Type.KeyOf(
Type.Object({
column: Type.String(),
'column-reverse': Type.String(),
row: Type.String(),
'row-reverse': Type.String(),
})
),
Type.Array(
Type.KeyOf(
Type.Object({
column: Type.String(),
'column-reverse': Type.String(),
row: Type.String(),
'row-reverse': Type.String(),
})
)
),
])
)
).toEqual('column');
});
});

View File

@ -8,6 +8,7 @@ import {
StringKind,
TSchema,
OptionalModifier,
UnionKind,
} from '@sinclair/typebox';
export function parseTypeBox(tSchema: TSchema): Static<typeof tSchema> {
@ -15,25 +16,30 @@ export function parseTypeBox(tSchema: TSchema): Static<typeof tSchema> {
return undefined;
}
switch (tSchema.kind) {
case StringKind:
switch (true) {
case tSchema.type === 'string' && 'enum' in tSchema && tSchema.enum.length > 0:
return tSchema.enum[0];
case tSchema.kind === StringKind:
return '';
case BooleanKind:
case tSchema.kind === BooleanKind:
return false;
case ArrayKind:
case tSchema.kind === ArrayKind:
return [];
case NumberKind:
case tSchema.kind === NumberKind:
case tSchema.kind === IntegerKind:
return 0;
case IntegerKind:
return 0;
case ObjectKind:
case tSchema.kind === ObjectKind: {
const obj: Static<typeof tSchema> = {};
for (const key in tSchema.properties) {
obj[key] = parseTypeBox(tSchema.properties[key]);
}
return obj;
}
case tSchema.kind === UnionKind && 'anyOf' in tSchema && tSchema.anyOf.length > 0:
case tSchema.kind === UnionKind && 'oneOf' in tSchema && tSchema.oneOf.length > 0: {
const subSchema = (tSchema.anyOf || tSchema.oneOf)[0];
return parseTypeBox(subSchema);
}
default:
return {};
}