forked from Twipped/joi-to-swagger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
363 lines (286 loc) · 8.89 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
'use strict';
var joi = require('joi');
var find = require('lodash.find');
var get = require('lodash.get');
var set = require('lodash.set');
var merge = require('lodash.merge');
var patterns = {
alphanum: '^[a-zA-Z0-9]*$',
alphanumLower: '^[a-z0-9]*$',
alphanumUpper: '^[A-Z0-9]*$',
};
module.exports = exports = function parse (schema, existingComponents) {
// inspect(schema);
if (!schema) throw new Error('No schema was passed.');
if (typeof schema === 'object' && !schema.isJoi) {
schema = joi.object().keys(schema);
}
if (!schema.isJoi) throw new TypeError('Passed schema does not appear to be a joi schema.');
var override = meta(schema, 'swagger');
if (override && meta(schema, 'swaggerOverride')) {
return { swagger: override, components: {} };
}
var metaDefName = meta(schema, 'className');
var metaDefType = meta(schema, 'classTarget') || 'schemas';
// if the schema has a definition class name, and that
// definition is already defined, just use that definition
if (metaDefName && get(existingComponents, [ metaDefType, metaDefName ])) {
return { swagger: refDef(metaDefType, metaDefName) };
}
var swagger;
var components = {};
if (parseAsType[schema._type]) {
swagger = parseAsType[schema._type](schema, existingComponents, components);
} else {
throw new TypeError(`${schema._type} is not a recognized Joi type.`);
}
if (!swagger) return { swagger, components };
if (schema._valids && schema._valids.has(null)) {
swagger.nullable = true;
}
if (schema._description) {
swagger.description = schema._description;
}
if (schema._examples.length) {
if (schema._examples.length === 1) {
swagger.example = schema._examples[0];
} else {
swagger.examples = schema._examples;
}
}
var label = get(schema, '_flags.label');
if (label) {
swagger.title = label;
}
var defaultValue = get(schema, '_flags.default');
if (defaultValue && typeof defaultValue !== 'function') {
swagger.default = defaultValue;
}
if (metaDefName) {
set(components, [ metaDefType, metaDefName ], swagger);
return { swagger: refDef(metaDefType, metaDefName), components };
}
if (override) {
Object.assign(swagger, override);
}
if (get(schema, '_flags.presence') === 'forbidden') {
return false;
}
return { swagger, components };
};
var parseAsType = {
number: (schema) => {
var swagger = {};
if (find(schema._tests, { name: 'integer' })) {
swagger.type = 'integer';
} else {
swagger.type = 'number';
if (find(schema._tests, { name: 'precision' })) {
swagger.format = 'double';
} else {
swagger.format = 'float';
}
}
if (find(schema._tests, { name: 'positive' })) {
swagger.minimum = 1;
}
if (find(schema._tests, { name: 'negative' })) {
swagger.maximum = -1;
}
var min = find(schema._tests, { name: 'min' });
if (min) {
swagger.minimum = min.arg;
}
var max = find(schema._tests, { name: 'max' });
if (max) {
swagger.maximum = max.arg;
}
var valids = schema._valids.values().filter((s) => typeof s === 'number');
if (get(schema, '_flags.allowOnly') && valids.length) {
swagger.enum = valids;
}
return swagger;
},
string: (schema) => {
var swagger = { type: 'string' };
if (get(schema, '_flags.presence') === 'forbidden') {
return false;
}
var strict = get(schema, '_settings.convert') === false;
if (find(schema._tests, { name: 'alphanum' })) {
if (strict && find(schema._tests, { name: 'lowercase' })) {
swagger.pattern = patterns.alphanumLower;
} else if (strict && find(schema._tests, { name: 'uppercase' })) {
swagger.pattern = patterns.alphanumUpper;
} else {
swagger.pattern = patterns.alphanum;
}
}
if (find(schema._tests, { name: 'token' })) {
if (find(schema._tests, { name: 'lowercase' })) {
swagger.pattern = patterns.alphanumLower;
} else if (find(schema._tests, { name: 'uppercase' })) {
swagger.pattern = patterns.alphanumUpper;
} else {
swagger.pattern = patterns.alphanum;
}
}
if (find(schema._tests, { name: 'email' })) {
swagger.format = 'email';
if (swagger.pattern) delete swagger.pattern;
}
if (find(schema._tests, { name: 'isoDate' })) {
swagger.format = 'date-time';
if (swagger.pattern) delete swagger.pattern;
}
var pattern = find(schema._tests, { name: 'regex' });
if (pattern) {
swagger.pattern = pattern.arg.pattern.toString().slice(1, -1);
}
for (let i = 0; i < schema._tests.length; i++) {
const test = schema._tests[i];
if (test.name === 'min') {
swagger.minLength = test.arg;
}
if (test.name === 'max') {
swagger.maxLength = test.arg;
}
if (test.name === 'length') {
swagger.minLength = test.arg;
swagger.maxLength = test.arg;
}
}
var valids = schema._valids.values().filter((s) => typeof s === 'string');
if (get(schema, '_flags.allowOnly') && valids.length) {
swagger.enum = valids;
}
return swagger;
},
binary: (schema) => {
var swagger = { type: 'string', format: 'binary' };
if (get(schema, '_flags.presence') === 'forbidden') {
return false;
}
if (get(schema, '_flags.encoding') === 'base64') {
swagger.format = 'byte';
}
for (let i = 0; i < schema._tests.length; i++) {
const test = schema._tests[i];
if (test.name === 'min') {
swagger.minLength = test.arg;
}
if (test.name === 'max') {
swagger.maxLength = test.arg;
}
if (test.name === 'length') {
swagger.minLength = test.arg;
swagger.maxLength = test.arg;
}
}
return swagger;
},
date: (schema) => {
if (get(schema, '_flags.presence') === 'forbidden') {
return false;
}
return { type: 'string', format: 'date-time' };
},
boolean: (schema) => {
if (get(schema, '_flags.presence') === 'forbidden') {
return false;
}
return { type: 'boolean' };
},
alternatives: (schema, existingComponents, newComponentsByRef) => {
var index = meta(schema, 'swaggerIndex') || 0;
var matches = get(schema, [ '_inner', 'matches' ]);
var firstItem = get(matches, [ 0 ]);
var itemsSchema;
if (firstItem.ref) {
if (schema._baseType && !firstItem.otherwise) {
itemsSchema = index ? firstItem.then : schema._baseType;
} else {
itemsSchema = index ? firstItem.otherwise : firstItem.then;
}
} else if (index) {
itemsSchema = get(matches, [ index, 'schema' ]);
} else {
itemsSchema = firstItem.schema;
}
var items = exports(itemsSchema, merge({}, existingComponents || {}, newComponentsByRef || {}));
if (get(itemsSchema, '_flags.presence') === 'required') {
items.swagger.__required = true;
}
merge(newComponentsByRef, items.components || {});
return items.swagger;
},
array: (schema, existingComponents, newComponentsByRef) => {
var index = meta(schema, 'swaggerIndex') || 0;
var itemsSchema = get(schema, [ '_inner', 'items', index ]);
if (!itemsSchema) throw Error('Array schema does not define an items schema at index ' + index);
if (get(itemsSchema, '_flags.presence') === 'forbidden') {
return false;
}
var items = exports(itemsSchema, merge({}, existingComponents || {}, newComponentsByRef || {}));
merge(newComponentsByRef, items.components || {});
var swagger = { type: 'array' };
for (let i = 0; i < schema._tests.length; i++) {
const test = schema._tests[i];
if (test.name === 'min') {
swagger.minItems = test.arg;
}
if (test.name === 'max') {
swagger.maxItems = test.arg;
}
if (test.name === 'length') {
swagger.minItems = test.arg;
swagger.maxItems = test.arg;
}
}
if (find(schema._tests, { name: 'unique' })) {
swagger.uniqueItems = true;
}
swagger.items = items.swagger;
return swagger;
},
object: (schema, existingComponents, newComponentsByRef) => {
var requireds = [];
var properties = {};
var combinedComponents = merge({}, existingComponents || {}, newComponentsByRef || {});
var children = get(schema, '_inner.children') || [];
children.forEach((child) => {
var key = child.key;
var prop = exports(child.schema, combinedComponents);
if (!prop.swagger) { // swagger is falsy if joi.forbidden()
return;
}
merge(newComponentsByRef, prop.components || {});
merge(combinedComponents, prop.components || {});
properties[key] = prop.swagger;
if (get(child, 'schema._flags.presence') === 'required' || prop.swagger.__required) {
requireds.push(key);
delete prop.swagger.__required;
}
});
var swagger = { type: 'object' };
if (requireds.length) {
swagger.required = requireds;
}
swagger.properties = properties;
if (get(schema, '_flags.allowUnknown') === false) {
swagger.additionalProperties = false;
}
return swagger;
},
};
function meta (schema, key) {
var flattened = Object.assign.apply(null, [ {} ].concat(schema._meta));
return get(flattened, key);
}
function refDef (type, name) {
return { $ref: '#/components/' + type + '/' + name };
}
// var inspectU = require('util').inspect;
// function inspect (value) {
// console.error(inspectU(value, { colors: true, depth: 10 }));
// }