Skip to content

Commit e467aa5

Browse files
authored
feat: support arrays of types using anyOf (#13)
1 parent 7a107e7 commit e467aa5

File tree

2 files changed

+75
-21
lines changed

2 files changed

+75
-21
lines changed

Diff for: index.js

+10-21
Original file line numberDiff line numberDiff line change
@@ -122,28 +122,17 @@ 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+
delete schema.type;
135+
schema.anyOf = typesWithoutNull.map(type => ({ type }));
147136
}
148137
}
149138
else if (schema.type === 'null') {

Diff for: test/type-array-split.test.js

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
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+
anyOf: [
51+
{ type: 'string' },
52+
{ type: 'number' },
53+
],
54+
},
55+
arrayWithMultipleTypes: {
56+
anyOf: [
57+
{ type: 'string' },
58+
{ type: 'number' },
59+
],
60+
},
61+
}
62+
};
63+
64+
should(result).deepEqual(expected, 'converted');
65+
});

0 commit comments

Comments
 (0)