diff --git a/packages/runtime/__tests__/parseTypeBox.spec.ts b/packages/runtime/__tests__/parseTypeBox.spec.ts index 931bc1cd..5d9209af 100644 --- a/packages/runtime/__tests__/parseTypeBox.spec.ts +++ b/packages/runtime/__tests__/parseTypeBox.spec.ts @@ -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'); + }); }); diff --git a/packages/runtime/src/utils/parseTypeBox.ts b/packages/runtime/src/utils/parseTypeBox.ts index 3079bd40..c97f4716 100644 --- a/packages/runtime/src/utils/parseTypeBox.ts +++ b/packages/runtime/src/utils/parseTypeBox.ts @@ -8,6 +8,7 @@ import { StringKind, TSchema, OptionalModifier, + UnionKind, } from '@sinclair/typebox'; export function parseTypeBox(tSchema: TSchema): Static { @@ -15,25 +16,30 @@ export function parseTypeBox(tSchema: TSchema): Static { 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 = {}; 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 {}; }