From f905c828a5e2ab1f32f831b245d1d381895c6628 Mon Sep 17 00:00:00 2001 From: Lukas Boll Date: Tue, 10 Oct 2023 11:04:18 +0200 Subject: [PATCH] fix(core): Recognize enums without type-attribute Previously, enums without type-attribute weren't recognized by the derive types function, leading to omitted enums in generated uischemas. Closes #2177 --- packages/core/src/util/util.ts | 12 +++++++++++- packages/core/test/util/derivetype.test.ts | 17 +++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/packages/core/src/util/util.ts b/packages/core/src/util/util.ts index 467cc8ec0..43a4cc6b3 100644 --- a/packages/core/src/util/util.ts +++ b/packages/core/src/util/util.ts @@ -77,7 +77,17 @@ export const deriveTypes = (jsonSchema: JsonSchema): string[] => { if (!isEmpty(jsonSchema.items)) { return ['array']; } - + if (!isEmpty(jsonSchema.enum)) { + const types: Set = new Set(); + jsonSchema.enum.forEach((enumElement) => { + if (typeof enumElement === 'string') { + types.add('string'); + } else { + deriveTypes(enumElement).forEach((type) => types.add(type)); + } + }); + return Array.from(types); + } if (!isEmpty(jsonSchema.allOf)) { const allOfType = find( jsonSchema.allOf, diff --git a/packages/core/test/util/derivetype.test.ts b/packages/core/test/util/derivetype.test.ts index 0772d36cb..38432f142 100644 --- a/packages/core/test/util/derivetype.test.ts +++ b/packages/core/test/util/derivetype.test.ts @@ -65,6 +65,23 @@ test('derive type w/o type - items array', (t) => { t.is(deriveTypes(schema)[0], 'array'); }); +test('derive type w/o type - enum', (t) => { + const schema: JsonSchema = { + enum: ['foo', 'bar'], + }; + t.is(deriveTypes(schema).length, 1); + t.is(deriveTypes(schema)[0], 'string'); +}); + +test('derive type w/o type - enum with two types', (t) => { + const schema: JsonSchema = { + enum: ['foo', 'bar', { properties: { foo: { type: 'string' } } }], + }; + t.is(deriveTypes(schema).length, 2); + t.is(deriveTypes(schema)[0], 'string'); + t.is(deriveTypes(schema)[1], 'object'); +}); + test('derive type with type - union', (t) => { const schema: JsonSchema = { type: ['string', 'number'],