forked from swagger-autogen/swagger-autogen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
swagger-autogen.js
375 lines (337 loc) · 14.2 KB
/
swagger-autogen.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
require('./src/prototype-functions');
const fs = require('fs');
const swaggerTags = require('./src/swagger-tags');
const handleFiles = require('./src/handle-files');
const statics = require('./src/statics');
const utils = require('./src/utils');
const handleData = require('./src/handle-data');
const merge = require('deepmerge');
const { platform } = process;
const symbols = platform === 'win32' ? { success: '', failed: '' } : { success: '✔', failed: '✖' };
let options = null;
let recLang = null;
module.exports = function (args, endpointsFiles, data) {
let outputFile = null;
options = {
language: null,
disableLogs: false,
disableWarnings: false,
openapi: null,
autoHeaders: true,
autoQuery: true,
autoBody: true,
autoResponse: true,
sortParameters: 'natural', // in test
sanitizeOutputData: false,
writeOutputFile: true
};
if (args && endpointsFiles) {
outputFile = args;
args = null;
}
if (args && typeof args === 'string') {
// will be deprecated in a future version
recLang = args;
} else if (args && typeof args === 'object') {
options = { ...options, ...args };
}
options.language = recLang || options.language || 'en-US';
handleFiles.setOptions(options);
handleData.setOptions(options);
utils.setOptions(options);
swaggerTags.setLanguage(recLang || options.language || 'en-US');
swaggerTags.setOpenAPI(options.openapi);
swaggerTags.setDisableLogs(options.disableLogs);
if(outputFile && endpointsFiles){
return init(outputFile, endpointsFiles, data);
} else {
return async (outputFile, endpointsFiles, data) => init(outputFile, endpointsFiles, data);
}
};
const init = async (outputFile, endpointsFiles, data) => {
try {
if (!outputFile) throw console.error("\nError: 'outputFile' was not specified.");
if (!endpointsFiles) throw console.error("\nError: 'endpointsFiles' was not specified.");
const legacyOutputFile = outputFile
if (platform === 'win32') {
let basePath = process.argv[1].split('\\').slice(0, -1).join('\\');
basePath = basePath.replaceAll('\\', '/');
outputFile = await handleFiles.resolvePathFile(outputFile, basePath);
} else if (outputFile.split(new RegExp("^/")).length == 1 && process && process.argv[1]) {
let basePath = process.argv[1].split('/').slice(0, -1).join('/');
outputFile = await handleFiles.resolvePathFile(outputFile, basePath);
}
let allFiles = [];
// Checking if endpoint files exist
for (let idx = 0; idx < endpointsFiles.length; ++idx) {
let file = endpointsFiles[idx];
const legacyFilePath = file;
if (platform === 'win32') {
let basePath = process.argv[1].split('\\').slice(0, -1).join('\\');
basePath = basePath.replaceAll('\\', '/');
file = await handleFiles.resolvePathFile(file, basePath);
} else if (file.split(new RegExp("^/")).length == 1 && process && process.argv[1]) {
let basePath = process.argv[1].split('/').slice(0, -1).join('/');
file = await handleFiles.resolvePathFile(file, basePath);
}
if (file.includes('*')) {
const patternPath = await utils.resolvePatternPath(file)
if (patternPath) {
for (let idxFile = 0; idxFile < patternPath.length; ++idxFile) {
let file = patternPath[idxFile]
let extension = await utils.getExtension(file);
if (!fs.existsSync(file + extension)) {
throw console.error("[swagger-autogen]: Error! File not found: '" + file + "'");
} else {
patternPath[idxFile] = file + extension;
}
}
allFiles = [...allFiles, ...patternPath];
}
} else {
let extension = await utils.getExtension(file);
if (!fs.existsSync(file + extension)) {
file = legacyFilePath; // To legacy cases. Will be deprecated in the future
if (!fs.existsSync(file + extension)) {
throw console.error("[swagger-autogen]: Error! File not found: '" + file + "'");
}
}
allFiles = [...allFiles, file + extension];
}
}
const objDoc = { ...statics.TEMPLATE, ...data, paths: {} };
if (options.openapi && utils.isNumeric(options.openapi.replaceAll('.', ''))) {
objDoc.openapi = options.openapi;
} else {
objDoc.swagger = '2.0';
}
// Removing all null attributes
for (let key in objDoc) {
if (objDoc[key] === null) {
delete objDoc[key];
}
}
if (!objDoc.info.version) {
objDoc.info.version = statics.TEMPLATE.info.version;
}
if (!objDoc.info.title) {
objDoc.info.title = statics.TEMPLATE.info.title;
}
if (!objDoc.info.description) {
objDoc.info.description = statics.TEMPLATE.info.description;
}
for (let file = 0; file < allFiles.length; file++) {
const filePath = allFiles[file];
const resp = fs.existsSync(filePath);
if (!resp) {
console.error('[swagger-autogen]: Error! Endpoint file not found => ' + "'" + filePath + "'");
if (!options.disableLogs) {
console.log('Swagger-autogen:', '\x1b[31m', 'Failed ' + symbols.failed, '\x1b[0m');
}
return false;
}
let relativePath = filePath.split('/');
if (relativePath.length > 1) {
relativePath.pop();
relativePath = relativePath.join('/');
} else {
relativePath = null;
}
let obj = await handleFiles.readEndpointFile(filePath, '', relativePath, []);
if (obj === false) {
if (!options.disableLogs) {
console.log('Swagger-autogen:', '\x1b[31m', 'Failed ' + symbols.failed, '\x1b[0m');
}
return false;
}
objDoc.paths = merge(objDoc.paths, obj, {
arrayMerge: overwriteMerge
});
}
let constainXML = false;
if (JSON.stringify(objDoc).includes('application/xml')) {
// REFACTOR: improve this
constainXML = true;
}
if (Object.keys(objDoc.definitions).length == 0 && objDoc.definition) {
objDoc.definitions = objDoc.definition
delete objDoc.definition
}
Object.keys(objDoc.definitions).forEach(definition => {
if (constainXML) {
objDoc.definitions[definition] = { ...swaggerTags.formatDefinitions(objDoc.definitions[definition], {}, constainXML), xml: { name: definition } };
} else {
objDoc.definitions[definition] = { ...swaggerTags.formatDefinitions(objDoc.definitions[definition], {}, constainXML) };
}
});
if (objDoc['@definitions']) {
if (!objDoc.definitions) {
objDoc.definitions = {};
}
objDoc.definitions = { ...objDoc.definitions, ...objDoc['@definitions'] };
delete objDoc['@definitions'];
}
/**
* Forcing convertion to OpenAPI 3.x
*/
if (objDoc.openapi) {
if (!objDoc.servers || objDoc.servers.length == 0) {
if (objDoc.host) {
if (objDoc.basePath) {
objDoc.host += objDoc.basePath
}
if (objDoc.host.slice(0, 4).toLowerCase() != 'http') {
if (objDoc.schemes && objDoc.schemes.length > 0) {
objDoc.schemes.forEach(scheme => {
objDoc.servers.push(
{
url: scheme + '://' + objDoc.host
}
)
})
} else {
objDoc.host = 'http://' + objDoc.host
objDoc.servers = [
{
url: objDoc.host
}
]
}
}
delete objDoc.host
} else {
delete objDoc.servers
}
} else {
delete objDoc.host
}
if (objDoc.components && objDoc.components.schemas) {
Object.keys(objDoc.components.schemas).forEach(schema => {
if (constainXML) {
objDoc.components.schemas[schema] = { ...swaggerTags.formatDefinitions(objDoc.components.schemas[schema], {}, constainXML), xml: { name: schema } };
} else {
objDoc.components.schemas[schema] = { ...swaggerTags.formatDefinitions(objDoc.components.schemas[schema], {}, constainXML) };
}
});
}
if (objDoc.components && objDoc.components['@schemas']) {
if (!objDoc.components) {
objDoc.components = {};
}
if (!objDoc.components.schemas) {
objDoc.components.schemas = {};
}
objDoc.components.schemas = { ...objDoc.components.schemas, ...objDoc.components['@schemas'] };
delete objDoc.components['@schemas'];
}
if (objDoc.components && objDoc.components.examples) {
Object.keys(objDoc.components.examples).forEach(example => {
if (!objDoc.components.examples[example].value) {
let auxExample = { ...objDoc.components.examples[example] }
delete objDoc.components.examples[example]
objDoc.components.examples[example] = {
value: auxExample
}
}
});
}
if (objDoc.definitions && Object.keys(objDoc.definitions).length > 0) {
if (!objDoc.components) {
objDoc.components = {}
}
if (!objDoc.components.schemas) {
objDoc.components.schemas = {}
}
objDoc.components.schemas = {
...objDoc.components.schemas,
...objDoc.definitions
}
delete objDoc.definitions
}
if (objDoc.securityDefinitions && Object.keys(objDoc.securityDefinitions).length > 0) {
if (!objDoc.components) {
objDoc.components = {}
}
if (!objDoc.components.securitySchemes) {
objDoc.components.securitySchemes = {}
}
objDoc.components.securitySchemes = {
...objDoc.components.securitySchemes,
...objDoc.securityDefinitions
}
delete objDoc.securityDefinitions
}
if (objDoc.basePath) {
delete objDoc.basePath
}
if (objDoc.schemes) {
delete objDoc.schemes
}
if (objDoc.consumes) {
delete objDoc.consumes
}
if (objDoc.produces) {
delete objDoc.produces
}
if (objDoc.definitions) {
delete objDoc.definitions
}
}
/**
* Removing unused parameters
*/
if (objDoc.components && Object.keys(objDoc.components).length == 0) {
delete objDoc.components;
}
if (objDoc.servers && Object.keys(objDoc.servers).length == 0) {
delete objDoc.servers;
}
if(objDoc.tags && objDoc.tags.length == 0){
delete objDoc.tags;
}
if(objDoc.consumes && objDoc.consumes.length == 0){
delete objDoc.consumes;
}
if(objDoc.produces && objDoc.produces.length == 0){
delete objDoc.produces;
}
if(objDoc.definitions && Object.keys(objDoc.definitions).length == 0){
delete objDoc.definitions;
}
if (options.writeOutputFile) {
let dataJSON = JSON.stringify(objDoc, null, 2);
try {
fs.writeFileSync(outputFile, dataJSON);
} catch (err) {
try {
fs.writeFileSync(legacyOutputFile, dataJSON); // To legacy cases. Will be deprecated in the future
} catch (err) {
throw console.error("[swagger-autogen]: Error! Could not generate output file.\nInvalid path: '" + outputFile + "'");
}
}
}
if (!options.disableLogs) {
console.log('Swagger-autogen:', '\x1b[32m', 'Success ' + symbols.success, '\x1b[0m');
}
const objDocOrig = {...objDoc}
try {
if (options.sanitizeOutputData) {
return {
success: true,
data: JSON.parse(JSON.stringify(objDoc)) // Deleting 'undefined' parameters
};
}
return { success: true, data: objDocOrig };
} catch (err) {
return { success: true, data: objDoc };
}
} catch (err) {
if (!options.disableLogs) {
console.log('Swagger-autogen:', '\x1b[31m', 'Failed ' + symbols.failed, '\x1b[0m');
}
return { success: false, data: null };
}
};
const overwriteMerge = (destinationArray, sourceArray, options) => {
if (destinationArray || sourceArray || options) return sourceArray;
};