From 2be53913dcca123aa33f3271446e31b022955d70 Mon Sep 17 00:00:00 2001 From: Theo Ephraim Date: Tue, 21 Jul 2020 10:54:15 -0700 Subject: [PATCH] feat: support arrays of types using anyOf --- index.js | 31 ++++++----------- test/type-array-split.test.js | 65 +++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 21 deletions(-) create mode 100644 test/type-array-split.test.js diff --git a/index.js b/index.js index d8242cf..7466bd9 100644 --- a/index.js +++ b/index.js @@ -122,28 +122,17 @@ function convertTypes(schema) { validateType(schema.type); if (Array.isArray(schema.type)) { - - if (schema.type.length > 2 || !schema.type.includes('null')) { - throw new Error('Type of ' + schema.type.join(',') + ' is too confusing for OpenAPI to understand. Found in ' + JSON.stringify(schema)); + if (schema.type.includes('null')) { + schema.nullable = true; } - - switch (schema.type.length) { - case 0: - delete schema.type; - break; - - case 1: - if (schema.type === 'null') { - schema.nullable = true; - } - else { - schema.type = schema.type[0]; - } - break; - - default: - schema.type = schema.type.find(type => type !== 'null'); - schema.nullable = true; + const typesWithoutNull = schema.type.filter(type => type !== 'null'); + if (typesWithoutNull.length === 0) { + delete schema.type + } else if (typesWithoutNull.length === 1) { + schema.type = typesWithoutNull[0]; + } else { + delete schema.type; + schema.anyOf = typesWithoutNull.map(type => ({ type })); } } else if (schema.type === 'null') { diff --git a/test/type-array-split.test.js b/test/type-array-split.test.js new file mode 100644 index 0000000..565f961 --- /dev/null +++ b/test/type-array-split.test.js @@ -0,0 +1,65 @@ +'use strict'; + +const convert = require('../'); +const should = require('should'); + +it('splits type arrays correctly', async () => { + const schema = { + $schema: 'http://json-schema.org/draft-04/schema#', + type: 'object', + properties: { + emptyArray: { + type: [] + }, + arrayWithNull: { + type: ['null'] + }, + arrayWithSingleType: { + type: ['string'] + }, + arrayWithNullAndSingleType: { + type: ['null', 'string'], + }, + arrayWithNullAndMultipleTypes: { + type: ['null', 'string', 'number'], + }, + arrayWithMultipleTypes: { + type: ['string', 'number'], + }, + } + }; + + const result = await convert(schema); + + const expected = { + type: 'object', + properties: { + emptyArray: {}, + arrayWithNull: { + nullable: true, + }, + arrayWithSingleType: { + type: 'string', + }, + arrayWithNullAndSingleType: { + nullable: true, + type: 'string', + }, + arrayWithNullAndMultipleTypes: { + nullable: true, + anyOf: [ + { type: 'string' }, + { type: 'number' }, + ], + }, + arrayWithMultipleTypes: { + anyOf: [ + { type: 'string' }, + { type: 'number' }, + ], + }, + } + }; + + should(result).deepEqual(expected, 'converted'); +});