Skip to content

support arrays of types using anyOf #13

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 21, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 10 additions & 21 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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') {
Expand Down
65 changes: 65 additions & 0 deletions test/type-array-split.test.js
Original file line number Diff line number Diff line change
@@ -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');
});