From 2a2fd814460bff73d6a5928ca6df9a65e47650c2 Mon Sep 17 00:00:00 2001 From: Jon Ursenbach Date: Fri, 27 Aug 2021 14:36:40 -0700 Subject: [PATCH] fix: remove duplicate items from enums (#491) --- __tests__/lib/openapi-to-json-schema.test.js | 7 +++++++ src/lib/openapi-to-json-schema.js | 5 +++++ 2 files changed, 12 insertions(+) diff --git a/__tests__/lib/openapi-to-json-schema.test.js b/__tests__/lib/openapi-to-json-schema.test.js index 10b0c5cc..5eaaddd7 100644 --- a/__tests__/lib/openapi-to-json-schema.test.js +++ b/__tests__/lib/openapi-to-json-schema.test.js @@ -396,6 +396,13 @@ describe('`enum` support', () => { expect(toJSONSchema(schema)).toStrictEqual(schema); }); + + it('should fitler out duplicate items from an enum', () => { + expect(toJSONSchema({ type: 'string', enum: ['cat', 'cat', 'dog', 'dog', 'snake'] })).toStrictEqual({ + type: 'string', + enum: ['cat', 'dog', 'snake'], + }); + }); }); describe('`format` support', () => { diff --git a/src/lib/openapi-to-json-schema.js b/src/lib/openapi-to-json-schema.js index e3bc7947..3ef246af 100644 --- a/src/lib/openapi-to-json-schema.js +++ b/src/lib/openapi-to-json-schema.js @@ -412,6 +412,11 @@ function toJSONSchema(data, opts = {}) { } } + // Enums should not have duplicated items as those will break AJV validation. + if ('enum' in schema && Array.isArray(schema.enum)) { + schema.enum = [...new Set(schema.enum)]; + } + // Clean up any remaining `items` or `properties` schema fragments lying around if there's also polymorphism present. if ('allOf' in schema || 'anyOf' in schema || 'oneOf' in schema) { if ('properties' in schema) {