This repository has been archived by the owner on Dec 17, 2018. It is now read-only.
This repository is currently being migrated. It's locked while the migration is in progress.
forked from kminami/apib2swagger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
406 lines (382 loc) · 14.8 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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
var url = require('url'),
http = require('http'),
drafter = require('drafter.js'),
UriTemplate = require('uritemplate');
var apib2swagger = module.exports.convertParsed = function(apib) {
//console.log(JSON.stringify(apib, null, 4));
var swagger = {};
swagger.swagger = '2.0';
swagger.info = {
'title': apib.name,
'x-logo': {
url: "figo_logo.png"
},
'version': '',
'description': apib.description
}
apib.metadata.forEach(function(meta) {
//console.log(meta);
if (meta.name.toLowerCase() === 'host') {
var urlParts = url.parse(meta.value);
swagger.host = urlParts.host;
swagger.basePath = urlParts.pathname;
swagger.schemes = [urlParts.protocol.replace(':','')];
}
});
swagger.paths = {};
swagger.definitions = {};
swagger.tags = [];
apib.content.filter(function(content) {
return content.element === 'category';
}).forEach(function(category) {
// description in Resource group section is discarded
var groupName = category.attributes ? category.attributes.name : '';
category.content.forEach(function(content) {
if (content.element === 'resource') {
// (name, description) in Resource section are discarded
swaggerDefinitions(swagger.definitions, content);
swaggerPaths(swagger.paths, groupName, content);
} else if (content.element === 'copy') {
swaggerTagDescriptions(swagger.tags, groupName, content)
} else if (content.element === 'dataStructure') {
swagger.definitions[content.content[0].meta.id] = jsonSchemaFromMSON(content);
}
});
});
return swagger;
}
function swaggerPathName(uriTemplate) {
var params = {};
for (var i = 0; i < uriTemplate.expressions.length; i++) {
var exp = uriTemplate.expressions[i];
if (!exp.varspecs) continue;
if (exp.operator.symbol === '?') continue; // query
for (var j = 0; j < exp.varspecs.length; j++) {
var spec = exp.varspecs[j];
params[spec.varname] = '{' + spec.varname + '}';
}
}
return decodeURIComponent(uriTemplate.expand(params));
}
var swaggerDefinitions = function (definitions, resource) {
var scheme;
if (resource.name) {
scheme = searchDataStructure(resource.content); // Attributes 1
definitions[resource.name] = scheme ? scheme : {};
}
if (resource.model.content && resource.model.name) {
scheme = searchDataStructure(resource.model.content); // Attribute 2
definitions[resource.model.name + 'Model'] = scheme ? scheme : {};
}
};
var swaggerTagDescriptions = function (tags, name, resource) {
var entry = {
"name" : name,
"description" : resource.content
}
tags.push(entry);
};
var swaggerPaths = function (paths, tag, resource) {
var uriTemplate = UriTemplate.parse(resource.uriTemplate),
pathName = swaggerPathName(uriTemplate);
//path.parameters = swaggerParameters(resource.parameters, uriTemplate);
var pathParams = swaggerParameters(resource.parameters, uriTemplate); // for swagger ui
for (var k = 0; k < resource.actions.length; k++) {
var action = resource.actions[k];
//console.log(JSON.stringify(action));
//console.log("\n\n")
if (!action.attributes.uriTemplate) {
if (!paths[pathName]) paths[pathName] = {};
paths[pathName][action.method.toLowerCase()] = swaggerOperation(pathParams, uriTemplate, action, tag);
continue;
}
var attrUriTemplate = UriTemplate.parse(action.attributes.uriTemplate),
attrPathName = swaggerPathName(attrUriTemplate);
if (!paths[attrPathName]) paths[attrPathName] = {};
paths[attrPathName][action.method.toLowerCase()] = swaggerOperation([], attrUriTemplate, action, tag);
}
};
var swaggerOperation = function (pathParams, uriTemplate, action, tag) {
var operation = {
'responses': swaggerResponses(action.examples),
'summary': action.name,
'description': action.description,
'tags': tag ? [tag] : [],
'parameters': pathParams.concat(swaggerParameters(action.parameters, uriTemplate))
};
var produces = {}, producesExist = false;
for (var key in operation.responses) {
var response = operation.responses[key];
for (var mime in response.examples) {
producesExist = true;
produces[mime] = true;
}
}
if (producesExist) {
operation.produces = [];
for (var mime in produces) {
operation.produces.push(mime);
}
}
// body parameter (schema)
var schema = [],
scheme = searchDataStructure(action.content); // Attributes 3
if (scheme) schema.push(scheme);
for (var j = 0; j < action.examples.length; j++) {
var example = action.examples[j];
for (var l = 0; l < example.requests.length; l++) {
var request = example.requests[l];
if (request.schema) { // Schema section in Request section
try {
// referencing Model's Schema is also here (no need to referencing definitions)
scheme = JSON.parse(request.schema);
if (scheme) {
for (var key in scheme.properties) {
// TODO: better check of array types
if (scheme.properties[key].type === 'array') {
scheme.properties[key].items = {"type":"strings", "enum" : []};
body = JSON.parse(request.body);
if (body[key] !== 'undefined') {
scheme.properties[key].items.enum = body[key];
}
} else {
body = JSON.parse(request.body);
scheme.properties[key].example = body[key];
}
}
schema.push(scheme);
}
} catch (e) {}
} else {
scheme = searchDataStructure(request.content); // Attributes 4
if (scheme) schema.push(scheme);
if (request.reference) {
schema.push({'$ref': '#/definitions/' + request.reference.id + 'Model'});
}
}
}
}
if (schema.length == 1) {
operation.parameters.push({name: 'body', in: 'body', schema: schema[0]});
} else if (schema.length > 1) {
operation.parameters.push({name: 'body', in: 'body', schema: {anyOf: schema}});
}
return operation;
}
function swaggerParameters(parameters, uriTemplate) {
var PARAM_TYPES = {
'string': 'string',
'number': 'number',
'integer': 'integer',
'boolean': 'boolean', 'bool': 'boolean',
'array': 'array',
'file': 'file',
'enum' : 'enum'
}
var params = [];
for (var l = 0; l < parameters.length; l++) {
var parameter = parameters[l];
//console.log(parameter);
// in = ["query", "header", "path", "formData", "body"]
var param = {
'name': parameter.name,
'in': getParamType(parameter.name, uriTemplate),
'description': parameter.description,
'required': parameter.required
}
var paramType = undefined;
if (PARAM_TYPES.hasOwnProperty(parameter.type)) {
paramType = PARAM_TYPES[parameter.type];
} else {
paramType = 'string';
}
var allowedValues = []
for (var j = 0; j < parameter.values.length; j++) {
allowedValues.push(parameter.values[j].value);
}
var parameterDefault = undefined;
if (parameter.default) {
if (paramType === 'number' || paramType === 'integer') {
parameterDefault = Number(parameter.default);
} else if (paramType === 'boolean') {
parameterDefault = (parameter.default == 'true')
} else {
parameterDefault = parameter.default;
}
}
// Body parameters has all info in schema
if (param.in === 'body') {
param.schema = {
'type': paramType
}
if (allowedValues.length > 0) {
param.schema.enum = allowedValues;
}
if (typeof parameterDefault !== 'undefined') {
param.schema.default = parameterDefault;
}
}
else {
param.type = paramType;
if (typeof parameterDefault !== 'undefined') {
param.default = parameterDefault;
}
if (allowedValues.length > 0) {
param.enum = allowedValues;
}
}
params.push(param);
}
return params;
}
var searchDataStructure = function (contents) {
for (var i = 0; i < contents.length; i++) {
var content = contents[i];
if (content.element !== "dataStructure") continue;
return jsonSchemaFromMSON(content);
}
};
var jsonSchemaFromMSON = function (content) {
// for apib._version = "4.0"
var mson = content.content[0];
if (mson.element === 'array') {
if (!mson.content || mson.content.length === 0) {
return {type: 'array', items: {}};
} else if (mson.content.length === 1) {
return {type: 'array', items: {'$ref': '#/definitions/' + mson.content[0].element}};
} else if (mson.content.length > 1) {
var items = [];
for (var i = 0; i < mson.content.length; i++) {
items.push({'$ref': '#/definitions/' + mson.content[i].element});
}
return {type: 'array', items: {'anyOf': items}};
}
}
if (mson.element !== 'object' && !mson.content) {
return {'$ref': '#/definitions/' + mson.element};
}
// object
var schema = {};
schema.type = 'object';
schema.required = [];
schema.properties = {};
for (var j = 0; j < mson.content.length; j++) {
var member = mson.content[j];
if (member.element !== "member") continue;
// MEMO: member.meta.description
if (member.content.value.element === 'array') {
// TODO: use member.content.value.content (schema for items)
local_items = {};
if (member.content.value.content.length > 1) {
local_items.type = member.content.value.content[0].type;
local_items.enum = [];
for (var p = 0; p < member.content.value.content.length; p++) {
local_items.enum.push(member.content.value.content[p].content)
}
}
schema.properties[member.content.key.content] = {type: 'array', items: local_items };
} else {
schema.properties[member.content.key.content] = {type: member.content.value.element};
}
if (!member.attributes || !member.attributes.typeAttributes) continue;
for (var k = 0; k < member.attributes.typeAttributes.length; k++) {
if (member.attributes.typeAttributes[k] === "required") {
schema.required.push(member.content.key.content);
}
}
}
// According to schema definition, required is a stringArray, which must be non-empty
if (schema.required.length === 0) {
delete schema.required
}
if (mson.element !== 'object') {
return {'allOf': [{'$ref':'#/definitions/' + mson.element}, schema]};
}
return schema;
};
function getParamType(name, uriTemplate) {
if (!uriTemplate) return 'body';
for (var i = 0; i < uriTemplate.expressions.length; i++) {
var exp = uriTemplate.expressions[i];
if (!exp.varspecs) continue;
for (var j = 0; j < exp.varspecs.length; j++) {
var spec = exp.varspecs[j];
if (spec.varname === name) {
return exp.operator.symbol === '?' ? 'query' : 'path';
}
}
}
return 'body'; // TODO: decide 'header', 'formData', 'body'
}
function fixArraySchema(schema) {
if (schema.type === 'array') {
if (!schema.hasOwnProperty('items')) schema.items = {};
} else if (schema.type === 'object') {
for (var k in schema.properties) fixArraySchema(schema.properties[k]);
}
}
function swaggerResponses(examples) {
var responses = {};
//console.log(examples);
for (var l = 0; l < examples.length; l++) {
var example = examples[l];
//console.log(example);
for (var m = 0; m < example.responses.length; m++) {
var response = example.responses[m];
//console.log(response);
var swaggerResponse = {
"description": response.description || http.STATUS_CODES[response.name],
"headers": {},
"examples": {}
};
if (response.schema) {
try {
swaggerResponse.schema = JSON.parse(response.schema);
delete swaggerResponse.schema['$schema'];
fixArraySchema(swaggerResponse.schema); // work around for Swagger UI / Editor
} catch (e) {}
}
if (!swaggerResponse.schema) {
var schema = searchDataStructure(response.content); // Attributes in response
if (schema) swaggerResponse.schema = schema;
}
for (var n = 0; n < response.headers.length; n++) {
var header = response.headers[n];
//swaggerResponse.headers[header.name] = {'type':'string'}
if (header.name === 'Content-Type') {
if (header.value.match(/application\/.*json/)) {
try {
swaggerResponse.examples[header.value] = JSON.parse(response.body);
} catch (e) {}
continue;
}
swaggerResponse.examples[header.value] = response.body;
}
}
responses[response.name] = swaggerResponse;
}
}
return responses;
}
exports.noconvert = function (data, callback) {
try {
var result = drafter.parse(data, {type: 'ast'});
return callback(null, result);
} catch (error) {
return callback(error, {});
}
};
exports.convert = function (data, callback) {
try {
var result = drafter.parse(data, {type: 'ast'});
//for (var i = 0; i < result.warnings.length; i++) {
// var warn = result.warnings[i];
// console.log(warn);
//}
var swagger = apib2swagger(result.ast);
return callback(null, {swagger: swagger});
}
catch (error) {
return callback(error, {});
}
};