forked from cdwv/oas3-api-snippet-enricher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
62 lines (48 loc) · 1.86 KB
/
index.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
'use strict';
const fs = require('fs');
const OpenAPISnippet = require('openapi-snippet');
const yaml = require('js-yaml');
const args = require('yargs').argv;
let targets = ['node_request','shell_curl', 'shell_httpie', 'python_python3', 'php_curl', 'php_http1', 'php_http2'];
if (args.targets) {
targets = args.targets.split(',');
}
function enrichSchema(schema){
for(var path in schema.paths){
for(var method in schema.paths[path]){
var generatedCode = OpenAPISnippet.getEndpointSnippets(schema, path, method, targets);
(schema.paths[path][method]["x-codeSamples"]) ? schema.paths[path][method]["x-codeSamples"] : schema.paths[path][method]["x-codeSamples"] = []
for(var snippetIdx in generatedCode.snippets){
var snippet = generatedCode.snippets[snippetIdx];
if (snippet.title.toLowerCase().includes('curl')) {
snippet.content = snippet.content.replace(/'Authorization: Basic REPLACE_BASIC_AUTH'/g, '"Authorization: Basic $(echo -n site_id:api_key | base64)"');
}
if (schema.paths[path][method]["x-codeSamples"].map(function(x) {return x.lang}).indexOf(snippet.title) < 0 ) {
schema.paths[path][method]["x-codeSamples"].push({ "lang": snippet.title, "source": snippet.content });
}
}
}
}
return schema;
}
if(!args.input){
throw new Error("Please pass the OpenAPI JSON schema as argument.");
}
// Try to interpret as YAML first, based on file extension
if(args.input.indexOf('yml') !== -1 || args.input.indexOf('yaml') !== -1){
try {
let schema = yaml.safeLoad(fs.readFileSync(args.input, 'utf8'));
schema = enrichSchema(schema);
console.log(JSON.stringify(schema));
} catch (e) {
// Do something with this
console.log(e);
}
} else {
fs.readFile(args.input, (err, data) => {
if (err) throw err;
let schema = JSON.parse(data);
schema = enrichSchema(schema);
console.log(JSON.stringify(schema));
});
}