Skip to content

Commit 5337cbd

Browse files
committed
support arrays of types using anyOf
1 parent 7a107e7 commit 5337cbd

File tree

2 files changed

+78
-21
lines changed

2 files changed

+78
-21
lines changed

index.js

Lines changed: 9 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -122,28 +122,16 @@ function convertTypes(schema) {
122122
validateType(schema.type);
123123

124124
if (Array.isArray(schema.type)) {
125-
126-
if (schema.type.length > 2 || !schema.type.includes('null')) {
127-
throw new Error('Type of ' + schema.type.join(',') + ' is too confusing for OpenAPI to understand. Found in ' + JSON.stringify(schema));
125+
if (schema.type.includes('null')) {
126+
schema.nullable = true;
128127
}
129-
130-
switch (schema.type.length) {
131-
case 0:
132-
delete schema.type;
133-
break;
134-
135-
case 1:
136-
if (schema.type === 'null') {
137-
schema.nullable = true;
138-
}
139-
else {
140-
schema.type = schema.type[0];
141-
}
142-
break;
143-
144-
default:
145-
schema.type = schema.type.find(type => type !== 'null');
146-
schema.nullable = true;
128+
const typesWithoutNull = schema.type.filter(type => type !== 'null');
129+
if (typesWithoutNull.length === 0) {
130+
delete schema.type
131+
} else if (typesWithoutNull.length === 1) {
132+
schema.type = typesWithoutNull[0];
133+
} else {
134+
schema.type = { anyOf: typesWithoutNull.map(type => ({ type })) };
147135
}
148136
}
149137
else if (schema.type === 'null') {

test/type-array-split.test.js

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
'use strict';
2+
3+
const convert = require('../');
4+
const should = require('should');
5+
6+
it('splits type arrays correctly', async () => {
7+
const schema = {
8+
$schema: 'http://json-schema.org/draft-04/schema#',
9+
type: 'object',
10+
properties: {
11+
emptyArray: {
12+
type: []
13+
},
14+
arrayWithNull: {
15+
type: ['null']
16+
},
17+
arrayWithSingleType: {
18+
type: ['string']
19+
},
20+
arrayWithNullAndSingleType: {
21+
type: ['null', 'string'],
22+
},
23+
arrayWithNullAndMultipleTypes: {
24+
type: ['null', 'string', 'number'],
25+
},
26+
arrayWithMultipleTypes: {
27+
type: ['string', 'number'],
28+
},
29+
}
30+
};
31+
32+
const result = await convert(schema);
33+
34+
const expected = {
35+
type: 'object',
36+
properties: {
37+
emptyArray: {},
38+
arrayWithNull: {
39+
nullable: true,
40+
},
41+
arrayWithSingleType: {
42+
type: 'string',
43+
},
44+
arrayWithNullAndSingleType: {
45+
nullable: true,
46+
type: 'string',
47+
},
48+
arrayWithNullAndMultipleTypes: {
49+
nullable: true,
50+
type: {
51+
anyOf: [
52+
{ type: 'string' },
53+
{ type: 'number' },
54+
]
55+
},
56+
},
57+
arrayWithMultipleTypes: {
58+
type: {
59+
anyOf: [
60+
{ type: 'string' },
61+
{ type: 'number' },
62+
]
63+
},
64+
},
65+
}
66+
};
67+
68+
should(result).deepEqual(expected, 'converted');
69+
});

0 commit comments

Comments
 (0)