forked from acacode/swagger-typescript-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswagger.js
53 lines (48 loc) · 1.5 KB
/
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
const _ = require('lodash');
const yaml = require('js-yaml');
const axios = require("axios");
const converter = require('swagger2openapi');
const { pathIsExist, getFileContent } = require("./files");
const parseSwaggerFile = (file) => {
if (typeof file !== "string") return file;
try {
return JSON.parse(file);
} catch (e) {
return yaml.safeLoad(file)
}
}
const getSwaggerFile = (pathToSwagger, urlToSwagger) => new Promise((resolve) => {
if (pathIsExist(pathToSwagger)){
console.log(`✨ try to get swagger by path "${pathToSwagger}"`)
resolve(getFileContent(pathToSwagger))
} else {
console.log(`✨ try to get swagger by url "${urlToSwagger}"`)
axios.get(urlToSwagger).then(res => resolve(res.data))
}
})
const getSwaggerObject = (pathToSwagger, urlToSwagger) =>
new Promise(resolve =>
getSwaggerFile(pathToSwagger, urlToSwagger).then(file => {
const swaggerSchema = parseSwaggerFile(file);
if (!(swaggerSchema.openapi)) {
converter.convertObj(swaggerSchema, {
warnOnly: true,
refSiblings: 'preserve',
rbname: "requestBodyName",
}, function(err, options){
const swaggerSchema = _.get(err, 'options.openapi', _.get(options, 'openapi'))
if (!swaggerSchema && err) {
throw new Error(err)
}
resolve(swaggerSchema)
});
} else {
resolve(swaggerSchema)
}
}).catch(e => {
throw new Error(e)
})
)
module.exports = {
getSwaggerObject,
}