forked from djfdyuruiry/swagger2-to-json
-
Notifications
You must be signed in to change notification settings - Fork 0
/
swagger2-to-json.js
executable file
·66 lines (55 loc) · 2.53 KB
/
swagger2-to-json.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
var fs = require("fs")
var request = require("sync-request")
var Swagger2Object = require("swagger2-to-object");
const toJson = (obj, opts) =>
(opts && opts.prettyPrint) ? JSON.stringify(obj, null, 4) : JSON.stringify(obj)
/* module function chain */
function convertSwagger (swaggerSpec, convertSwaggerOptions) {
var objGenerator = Swagger2Object.generateObjects().for();
var requestsAndResponsesJson = () => toJson(objGenerator.specSchemas(swaggerSpec, convertSwaggerOptions));
var requestsJson = () => toJson(objGenerator.specRequests(swaggerSpec, convertSwaggerOptions));
var responsesJson = () => toJson(objGenerator.specResponses(swaggerSpec, convertSwaggerOptions));
return {
requestsAndResponses: () => ({
toJson: (options) => requestsAndResponsesJson(),
toJsonFile: (filename, options) => fs.writeFileSync(filename, requestsAndResponsesJson())
}),
requests: () => ({
toJson: (options) => requestsJson(),
toJsonFile: (filename, options) => fs.writeFileSync(filename, requestsJson())
}),
responses: () => ({
toJson: (options) => responsesJson(),
toJsonFile: (filename, options) => fs.writeFileSync(filename, responsesJson())
}),
}
}
function convertSwaggerJson (swaggerJson, convertSwagger, options) {
if (options && options.debug) {
console.log(`Parsing Swagger spec JSON...`);
}
var swaggerSpec = JSON.parse(swaggerJson);
return convertSwagger(swaggerSpec, options);
}
/* module export */
module.exports = {
convertSwagger: () => ({
fromUrl: (url, options) => {
if (options && options.debug) {
console.log(`Reading Swagger spec from URL: ${url}...`);
}
var response = request("GET", url);
var swaggerJson = response.getBody();
return convertSwaggerJson(swaggerJson, convertSwagger, options);
},
fromFile: (filePath, options) => {
if (options && options.debug) {
console.log(`Reading Swagger spec from file: ${filePath}...`);
}
var swaggerJson = fs.readFileSync(filePath);
return convertSwaggerJson(swaggerJson, convertSwagger, options);
},
fromJson: (swaggerSpecJson, options) => convertSwaggerJson(swaggerJson, convertSwagger, options),
fromSpec: (swaggerSpec, options) => convertSwagger(swaggerSpec, options)
})
};