-
Notifications
You must be signed in to change notification settings - Fork 18
/
apidoc_to_swagger.js
358 lines (310 loc) · 10.1 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
var _ = require('lodash');
var { pathToRegexp } = require('path-to-regexp');
const { debug, log } = require('winston');
const GenerateSchema = require('generate-schema')
var swagger = {
openapi: "3.0.0",
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;
var obj = paths[url] = paths[url] || {};
_.extend(obj, generateProps(verb))
}
}
return paths;
}
function mapHeaderItem(i) {
return {
in: 'header',
name: i.field,
description: removeTags(i.description),
required: !i.optional,
schema: {
type: 'string',
default: i.defaultValue
}
}
}
function mapQueryItem(i) {
return {
in: 'query',
name: i.field,
description: removeTags(i.description),
required: !i.optional,
schema: {
type: 'string',
default: i.defaultValue
}
}
}
/**
* 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 = {
'': parameterInBody['schema']
}
apiDocParams.forEach(i => {
const type = i.type.toLowerCase()
const key = i.field
const nestedName = createNestedName(i.field)
const { objectName = '', propertyName } = nestedName
if (type.endsWith('object[]')) {
// 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: {}, required: [] } }
}
// 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,
// default: i.defaultValue,
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: {}, required: [] }
}
// new mount point
mountPlaces[key] = mountPlaces[objectName]['properties'][propertyName]
} else {
mountPlaces[objectName]['properties'][propertyName] = {
type,
description: i.description,
default: i.defaultValue,
}
}
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 body = generateBody(verb)
const responses = generateResponses(verb)
pathItemObject[verb.type] = {
tags: [verb.group],
summary: removeTags(verb.name),
description: removeTags(verb.title),
consumes: [
"application/json"
],
produces: [
"application/json"
],
parameters,
requestBody: {
content: {
'application/json': body
}
},
responses
}
return pathItemObject
}
function generateBody(verb) {
const mixedBody = []
if (verb && verb.parameter && verb.parameter.fields) {
const Parameter = verb.parameter.fields.Parameter || []
const _body = verb.parameter.fields.Body || []
mixedBody.push(..._body)
if (!(verb.type === 'get')) {
mixedBody.push(...Parameter)
}
}
let body = {}
if (verb.type === 'post' || verb.type === 'put') {
body = generateRequestBody(verb, mixedBody)
}
return body
}
function generateParameters(verb) {
const mixedQuery = []
const mixedBody = []
const header = verb && verb.header && verb.header.fields.Header || []
if (verb && verb.parameter && verb.parameter.fields) {
const Parameter = verb.parameter.fields.Parameter || []
const _query = verb.parameter.fields.Query || []
const _body = verb.parameter.fields.Body || []
mixedQuery.push(..._query)
mixedBody.push(..._body)
if (verb.type === 'get') {
mixedQuery.push(...Parameter)
} else {
mixedBody.push(...Parameter)
}
}
const parameters = []
parameters.push(...mixedQuery.map(mapQueryItem))
parameters.push(...header.map(mapHeaderItem))
parameters.push(...(verb.query || []).map(mapQueryItem))
return parameters
}
function generateRequestBody(verb, mixedBody) {
const bodyParameter = {
schema: {
properties: {},
type: 'object',
required: []
}
}
if (_.get(verb, 'parameter.examples.length') > 0) {
for (const example of verb.parameter.examples) {
const { code, json } = safeParseJson(example.content)
const schema = GenerateSchema.json(example.title, json)
bodyParameter.schema = schema
bodyParameter.description = example.title
}
}
transferApidocParamsToSwaggerBody(mixedBody, bodyParameter)
return bodyParameter
}
function generateResponses(verb) {
const success = verb.success
const responses = {
200: {
schema: {
properties: {},
type: 'object',
required: []
}
}
}
if (success && success.examples && success.examples.length > 0) {
for (const example of success.examples) {
const { code, json } = safeParseJson(example.content)
const schema = GenerateSchema.json(example.title, json)
responses[code] = { schema, description: example.title }
}
}
mountResponseSpecSchema(verb, responses)
return responses
}
function mountResponseSpecSchema(verb, responses) {
// if (verb.success && verb.success['fields'] && verb.success['fields']['Success 200']) {
if (_.get(verb, 'success.fields.Success 200')) {
const apidocParams = verb.success['fields']['Success 200']
responses[200] = transferApidocParamsToSwaggerBody(apidocParams, responses[200])
}
}
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 === '[') {
startingIndex = i;
break;
}
}
const mayCodeString = content.slice(0, startingIndex)
const mayContentString = content.slice(startingIndex)
const mayCodeSplit = mayCodeString.trim().split(' ')
const code = mayCodeSplit.length === 3 ? parseInt(mayCodeSplit[1]) : 200
let json = {}
try {
json = JSON.parse(mayContentString)
} catch (error) {
console.warn('parse %o with error', mayContentString, error)
}
return {
code,
json
}
}
function createNestedName(field, defaultObjectName) {
let propertyName = field;
let objectName;
let propertyNames = field.split(".");
if (propertyNames && propertyNames.length > 1) {
propertyName = propertyNames.pop();
objectName = propertyNames.join(".");
}
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: toSwagger
};