forked from acquia/apidoc-openapi-3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
apidoc_to_swagger.js
392 lines (341 loc) · 11.4 KB
/
apidoc_to_swagger.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
var _ = require('lodash');
var { pathToRegexp } = require('path-to-regexp');
const GenerateSchema = require('generate-schema');
var log;
function setLogger(logger) {
log = logger;
}
var swagger = {
openapi: '3.0.3',
info: {},
paths: {}
};
function toSwagger(apidocJson, projectJson) {
swagger.info = addInfo(projectJson);
swagger.paths = extractPaths(apidocJson);
// for (const key in swagger) {
// console.log('[%s] %o', key, swagger[key]);
// }
return swagger;
}
var tagsRegex = /(<([^>]+)>)/ig;
// Removes <p> </p> tags from text
function removeTags(text) {
return text ? text.replace(tagsRegex, "") : text;
}
function addInfo(projectJson) { // cf. https://swagger.io/specification/#info-object
var info = {};
info["title"] = projectJson.title || projectJson.name;
info["version"] = projectJson.version;
info["description"] = projectJson.description;
return info;
}
/**
* Extracts paths provided in json format
* post, patch, put request parameters are extracted in body
* get and delete are extracted to path parameters
* @param apidocJson
* @returns {{}}
*/
function extractPaths(apidocJson) { // cf. https://swagger.io/specification/#paths-object
var apiPaths = groupByUrl(apidocJson);
var paths = {};
for (var i = 0; i < apiPaths.length; i++) {
var verbs = apiPaths[i].verbs;
var url = verbs[0].url;
var pattern = pathToRegexp(url, null);
var matches = pattern.exec(url);
// Surrounds URL parameters with curly brackets -> :email with {email}
var pathKeys = [];
for (let j = 1; j < matches.length; j++) {
var key = matches[j].substr(1);
url = url.replace(matches[j], "{" + key + "}");
pathKeys.push(key);
}
for (let j = 0; j < verbs.length; j++) {
var verb = verbs[j];
var type = verb.type.toLowerCase();
verb.type = type
var obj = paths[url] = paths[url] || {};
_.extend(obj, generateProps(verb))
}
}
return paths;
}
function mapHeaderItem(i) {
return {
schema: {
type: 'string',
example: i.defaultValue
},
in: 'header',
name: i.field,
description: removeTags(i.description),
required: !i.optional,
example: i.defaultValue
}
}
function mapQueryItem(i) {
return {
schema: {
type: 'string',
example: i.defaultValue
},
in: 'query',
name: i.field,
description: removeTags(i.description),
required: !i.optional
}
}
function mapPathItem(i) {
return {
schema: {
type: 'string',
example: i.defaultValue
},
in: 'path',
name: i.field,
description: removeTags(i.description),
required: !i.optional
}
}
/**
* apiDocParams
* @param {type} type
* @param {boolean} optional
* @param {string} field
* @param {string} defaultValue
* @param {string} description
*/
/**
*
* @param {ApidocParameter[]} apiDocParams
* @param {*} parameter
*/
function transferApidocParamsToSwaggerBody(apiDocParams, parameterInBody) {
let mountPlaces = {
'': Object.values(parameterInBody)[0]['schema']
}
apiDocParams.forEach(i => {
if (/(<p>)*\[\w+\[\w+/.test(i.description)) return; // handle api doc error for deep nested fields
const type = i.type.toLowerCase()
const key = i.field
const nestedName = createNestedName(i.field, '')
const { objectName, propertyName } = nestedName
if (!mountPlaces[objectName]) mountPlaces[objectName] = { type: 'object', properties: {} };
else if (!mountPlaces[objectName]['properties']) mountPlaces[objectName]['properties'] = {};
if (type === 'object[]' || type === 'array') {
// if schema(parsed from example) doesn't has this constructure, init
if (!mountPlaces[objectName]['properties'][propertyName]) {
mountPlaces[objectName]['properties'][propertyName] = { type: 'array', items: { type: 'object', properties: {} } }
}
// new mount point
mountPlaces[key] = mountPlaces[objectName]['properties'][propertyName]['items']
} else if (type.endsWith('[]')) {
// if schema(parsed from example) doesn't has this constructure, init
if (!mountPlaces[objectName]['properties'][propertyName]) {
mountPlaces[objectName]['properties'][propertyName] = {
items: {
type: type.slice(0, -2), description: i.description,
example: i.defaultValue
},
type: 'array'
}
}
} else if (type === 'object') {
// if schema(parsed from example) doesn't has this constructure, init
if (!mountPlaces[objectName]['properties'][propertyName]) {
mountPlaces[objectName]['properties'][propertyName] = { type: 'object', properties: {} }
}
// new mount point
mountPlaces[key] = mountPlaces[objectName]['properties'][propertyName]
} else {
mountPlaces[objectName]['properties'][propertyName] = {
type,
description: i.description
}
}
if (!i.optional) {
// generate-schema forget init [required]
if (mountPlaces[objectName]['required']) {
mountPlaces[objectName]['required'].push(propertyName)
} else {
mountPlaces[objectName]['required'] = [propertyName]
}
}
})
return parameterInBody
}
function generateProps(verb) {
const pathItemObject = {}
const parameters = generateParameters(verb)
const responses = generateResponses(verb)
pathItemObject[verb.type] = {
tags: [verb.group],
operationId: removeTags(verb.name),
summary: removeTags(verb.name),
description: removeTags(verb.title || '') + (verb.description ? ' - ' + removeTags(verb.description) : ''),
parameters,
responses
}
if (verb.type === 'post' || verb.type === 'put' || verb.type === 'patch') {
pathItemObject[verb.type].requestBody = generateRequestBody(verb, verb.body)
}
return pathItemObject
}
function generateParameters(verb) {
const parameters = []
const header = verb && verb.header && verb.header.fields.Header || []
parameters.push(...header.map(mapHeaderItem))
if (verb && verb.parameter && verb.parameter.fields) {
const _path = verb.parameter.fields.Parameter || []
parameters.push(..._path.map(mapPathItem))
}
parameters.push(...(verb.query || []).map(mapQueryItem))
return parameters
}
function generateRequestBody(verb, mixedBody) {
const bodyParameter = {
content: {
'application/json': {
schema: {
properties: {},
type: 'object'
}
}
}
}
if (_.get(verb, 'parameter.examples.length') > 0) {
bodyParameter.content['application/json'].examples = {};
for (let i = 0; i < verb.parameter.examples.length; i++) {
const example = verb.parameter.examples[i];
const { code, json } = safeParseJson(example.content)
const schema = GenerateSchema.json(example.title, json)
delete schema.$schema;
bodyParameter.content['application/json'].schema = schema
bodyParameter.description = example.title
bodyParameter.content['application/json'].examples[i.toString()] = {
summary: example.title,
value: example.content
}
}
}
if (mixedBody)
transferApidocParamsToSwaggerBody(mixedBody, bodyParameter.content)
return bodyParameter
}
function generateResponses(verb) {
const success = verb.success
const error = verb.error
const responses = {}
if (success && success.examples) {
for (const example of success.examples) {
generateResponse(example, responses);
}
}
if (error && error.examples) {
for (const example of error.examples) {
generateResponse(example, responses);
}
}
let code2xx = Object.keys(responses).filter((r => (c = parseInt(r), 200 <= c && c < 300)))[0];
if (!code2xx) {
mountResponseSpecSchema(verb, responses);
responses[200] = {
content: {
'application/json': {
schema: {
properties: {},
type: 'object',
required: []
}
}
}
}
} else if (code2xx === '204') {
responses[204] = {
description: "No Content"
}
}
mountResponseSpecSchema(verb, responses, code2xx)
return responses
}
function generateResponse(example, responses) {
const { code, json } = safeParseJson(example.content);
const schema = GenerateSchema.json(example.title, json);
delete schema.$schema;
responses[code] = {
content: {
'application/json': {
example: json,
schema
}
},
description: example.title
};
}
function mountResponseSpecSchema(verb, responses, code2XX) {
// if (verb.success && verb.success['fields'] && verb.success['fields']['Success 200']) {
if (_.get(verb, 'success.fields.Success ' + code2XX)) {
const apidocParams = verb.success['fields']['Success ' + code2XX]
responses[code2XX].content = transferApidocParamsToSwaggerBody(apidocParams, responses[code2XX].content)
}
}
function safeParseJson(content) {
// such as 'HTTP/1.1 200 OK\n' + '{\n' + ...
let startingIndex = 0;
for (let i = 0; i < content.length; i++) {
const character = content[i];
if (character === '{' || character === '[' || character === '"') {
startingIndex = i;
break;
}
}
const mayCodeString = content.slice(0, startingIndex)
const mayContentString = content.slice(startingIndex)
const mayCodeSplit = mayCodeString.trim().split(' ')
let code = 200;
if (mayCodeSplit.length > 1 && mayCodeSplit[0].toLowerCase().startsWith("http")) {
let c = parseInt(mayCodeSplit[1]);
if (!isNaN(c)) code = c;
}
let json = {}
try {
json = JSON.parse(mayContentString)
} catch (error) {
console.debug('JSON parse error', content)
}
return {
code,
json
}
}
function createNestedName(field, defaultObjectName) {
let propertyName = field;
let objectName;
if (field.includes('.')) {
const fieldRegex = /\.(\w+)$/;
propertyName = field.match(fieldRegex)[1];
objectName = field.replace(fieldRegex, '');
} else if (field.includes('[')) {
const fieldRegex = /\[(\w+)\]/;
propertyName = field.match(fieldRegex)[1];
objectName = field.replace(fieldRegex, '')
}
return {
propertyName: propertyName,
objectName: objectName || defaultObjectName
}
}
function groupByUrl(apidocJson) {
return _.chain(apidocJson)
.groupBy("url")
.toPairs()
.map(function (element) {
return _.zipObject(["url", "verbs"], element);
})
.value();
}
module.exports = {
toSwagger, setLogger
};