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'); +});