-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
93 lines (78 loc) · 2.71 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/* eslint-disable no-underscore-dangle */
const alternativesParser = require('./parsersForTypes/alternatives');
const numberParser = require('./parsersForTypes/number');
const stringParser = require('./parsersForTypes/string');
const booleanParser = require('./parsersForTypes/boolean');
const objectParser = require('./parsersForTypes/object');
const arrayParser = require('./parsersForTypes/array');
const binaryParser = require('./parsersForTypes/binary');
const dateParser = require('./parsersForTypes/date');
const universalDecorator = (joiSchema) => {
const universalParams = {};
if (joiSchema._valids && joiSchema._valids.has(null)) {
universalParams.nullable = true;
}
if (joiSchema._valids && joiSchema._valids._set.size) {
const validValues = Array.from(joiSchema._valids._set);
const notEmptyValues = validValues.filter(value => value !== null && value !== '');
if (notEmptyValues.length) {
universalParams.enum = notEmptyValues;
}
}
if (joiSchema._description) {
universalParams.description = joiSchema._description;
}
if (joiSchema._flags.label) {
universalParams.title = joiSchema._flags.label;
}
if (joiSchema._flags.default) {
universalParams.default = joiSchema._flags.default;
}
if (joiSchema._examples && joiSchema._examples.length > 0) {
if (joiSchema._examples.length === 1) {
[universalParams.example] = joiSchema._examples;
} else {
universalParams.examples = joiSchema._examples;
}
}
return universalParams;
};
const convert = (joiSchema) => {
if (!joiSchema) throw new Error('No schema was passed.');
if (!joiSchema.isJoi) throw new TypeError('Passed schema does not appear to be a joi schema.');
const type = joiSchema._type;
let swaggerSchema;
switch (type) {
case 'number':
swaggerSchema = numberParser(joiSchema);
break;
case 'string':
swaggerSchema = stringParser(joiSchema);
break;
case 'boolean':
swaggerSchema = booleanParser(joiSchema);
break;
case 'binary':
swaggerSchema = binaryParser(joiSchema);
break;
case 'alternatives':
swaggerSchema = alternativesParser(joiSchema, convert);
break;
case 'object':
swaggerSchema = objectParser(joiSchema, convert);
break;
case 'array':
swaggerSchema = arrayParser(joiSchema, convert);
break;
case 'date':
swaggerSchema = dateParser(joiSchema);
break;
case 'any':
swaggerSchema = { type: ['array', 'boolean', 'number', 'object', 'string', 'null'] };
break;
default:
throw new TypeError(`${type} is not a recognized Joi type.`);
}
return Object.assign(swaggerSchema, universalDecorator(joiSchema));
};
module.exports = convert;