This repository has been archived by the owner on Jan 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
263 lines (232 loc) · 8.23 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
const _ = require('lodash');
module.exports.toSwagger = toSwagger;
module.exports.convert = convert;
/**
*
* @param {String} id - schema id
* @param {Ajv} validator
* @param {Int} [oas=2] - open api (swagger) specification version (2|3)
*
* @return {Function} - function which returns swagger parameters collection {Array}
*/
function toSwagger(id, validator, oas) {
var swagger
, schema = _.cloneDeep(validator.getSchema(id));
if (!schema) {
throw new Error(`Schema: ${id} not found`);
}
swagger = resolveSchemaRefs(schema.schema, validator);
swagger = convert(swagger, oas);
/**
* @param {Object} options
* @param {String} options.in - possible values: "formData", "body", "query", "path"
* @return {Array}
*/
return function toSwaggerJSON(options) {
var out = [];
options = options || {};
// the `build` always returns swagger `body` payload format (in=body)
// so we gotta handle conversion to the other formats (in=query|path|formData)
if ( options.in !== 'body'
&& swagger.type === 'object'
&& !swagger.hasComplexDataStructures
) {
var requiredProps = swagger.required || [];
Object.keys(swagger.properties || {}).forEach(function(name) {
let param = {
name: name,
in: options.in,
required: ~requiredProps.indexOf(name) ? true : false
};
if (oas >= 3) {
param.schema = swagger.properties[name];
} else {
Object.assign(param, swagger.properties[name]);
}
out.push(param);
});
} else {
//fall back to POST JSON body payload if data are of complex type
//and thus can't be described as simple form fields
if (options.in === 'formData' && swagger.hasComplexDataStructures) {
options.in = 'body';
} else if(options.in !== 'body' && swagger.hasComplexDataStructures) {
throw new Error('Swagger ' + options.in + ' parameter schema can NOT be constructed with complex data structures. Not supported.');
}
out.push(wrapSchema(swagger, options));
}
return out;
}
}
/**
* dereferences releative $refs and internal references to other ajv validator schemas
* @param {Object|Array} val - value
* @param {Ajv} validator
* @param {Object|Array} _root - initial value
* @return {Object}
*/
function resolveSchemaRefs(val, validator, _root) {
_root = _root || val;
resolve(val, '', val);
return val;
/*
* @param {mixed} val
* @param {String|Int} key
* @param {Object|Array} object
*/
function resolve(val, key, object) {
if (_.isPlainObject(val)) {
if ( val.hasOwnProperty('$ref')
&& typeof val.$ref === 'string'
) {
var resolved;
if (val.$ref.indexOf('#') === 0) {
let path = _.compact(val.$ref.slice(1).split('/'));
if (_.has(_root, path)) {
resolved = _.cloneDeep(_.get(_root, path));
Object.assign(resolved, _.omit(val, ['$ref']));
_.set(object, key, resolved);
}
} else if ((resolved = validator.getSchema(val.$ref))) {
resolved = _.cloneDeep(resolved.schema);
Object.assign(resolved, _.omit(val, ['$ref']));
_.set(object, key, resolved);
}
do {
resolve(resolved, key, object);
}
while ( _.isPlainObject(object[key])
&& object[key].hasOwnProperty('$ref')
);
} else {
_.forOwn(val, resolve);
}
} else if (val instanceof Array) {
val.forEach(resolve);
}
//can not return anything because of the lodash.forOwn
}
}
/**
*
* @param {Object} schema
* @param {Object} options
* @param {String} options.in - possible values: "formData", "body", "query", "path"
*
* @return {Object}
*/
function wrapSchema(schema, options) {
var out = {
description: schema.description || '',
in: options.in
};
if (options.in === 'body') {
out.name = 'JSON payload';
out.schema = _.cloneDeep(schema);
out.required = schema.required instanceof Array ? schema.required.length > 0 : false;
}
return out;
}
/**
* @param {Object} schema
* @param {Int} [oas=2] - open api (swagger) specification version (2|3)
* @param {Object} _parentSchema
*/
function convert(schema, oas, _parentSchema) {
oas = oas || 2;
schema = _.clone(schema) || {};
//make sure the `type` option is typeof string
if (schema.hasOwnProperty('type')) {
if ( schema.type instanceof Array
&& schema.type.length
&& schema.type.length <= 2
&& ~schema.type.indexOf('null')
) {
if (oas >= 3) { //since OAS 3.x
schema.nullable = true;
}
if (schema.type.length == 2) {
schema.type.splice(schema.type.indexOf('null'), 1);
}
schema.type = schema.type.shift();
} else if (schema.type instanceof Array && schema.type.length >= 2) {
//OAS does not support multi-type properties
//thus we must fallback to string type which can essentially be
//enything (see https://github.com/OAI/OpenAPI-Specification/issues/229)
schema.type = 'string';
}
}
//convert $desc -> description
if (schema.hasOwnProperty('$desc') && typeof schema.$desc === 'string') {
schema.description = schema.$desc;
delete schema.$desc;
}
//if the schema describes deep nested data structures, mark it as such
//so we can later decide how we will present the schema
if (_parentSchema && schema.type === 'object') {
Object.defineProperty(
_parentSchema,
'hasComplexDataStructures',
{
enumerable: false,
value: true
}
);
}
//Open API 2.0
if (oas === 2) {
//merge schemas into signle schema
//(conditions are not supported in OAS 2.0)
['oneOf', 'anyOf'].forEach(function(keyword) {
if ( schema.hasOwnProperty(keyword)
&& schema[keyword] instanceof Array
) {
_.merge(schema, _.merge.apply(_, schema[keyword]));
delete schema[keyword];
}
});
//simplify the "allOf" structure if it's used only for data coerction
//before validation
if ( schema.hasOwnProperty('allOf')
&& schema['allOf'] instanceof Array
) {
if (schema['allOf'].length === 2
&& _.isPlainObject(schema['allOf'][0])
&& _.isPlainObject(schema['allOf'][1])
&& Object.keys(schema['allOf'][0]).length === 1
&& schema['allOf'][0].hasOwnProperty('$toJSON')
) {
_.merge(schema, schema['allOf'][1]);
delete schema['allOf'];
} else if (schema['allOf'].length === 1) {
_.merge(schema, schema['allOf'][0]);
delete schema['allOf'];
}
}
}
//recursively iterate throught schema
[
'properties',
'patternProperties',
].forEach(function(keyword) {
if ( typeof schema[keyword] === 'object'
&& _.isPlainObject(schema[keyword])
) {
Object.keys(schema[keyword]).forEach(function(prop) {
schema[keyword][prop] = convert(schema[keyword][prop], oas, schema);
});
}
});
[
'items',
'additionalProperties',
'additionalItems'
].forEach(function(keyword) {
if ( typeof schema[keyword] === 'object'
&& _.isPlainObject(schema[keyword])
) {
schema[keyword] = convert(schema[keyword], oas, schema);
}
});
return schema;
}