This repository has been archived by the owner on Jun 11, 2021. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mashery2openapi.js
97 lines (80 loc) · 2.19 KB
/
mashery2openapi.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
var fs = require('fs');
var SwaggerParser = require('swagger-parser');
var _ = require('lodash');
var m2oa = require('./index.js');
var keep = {};
var valid = [];
var fails = 0;
function safeMkdir(dir){
try {
fs.mkdirSync(dir);
}
catch (ex) {}
return dir;
}
var options = {};
var fileOrUrl = process.argv.length>2 ? process.argv[2] : './test.html';
if (fileOrUrl.indexOf('://')<0) {
options.srcUrl = process.argv.length>3 ? process.argv[3] : 'http://developer.example.com';
}
console.log('in: '+fileOrUrl);
m2oa.convertHtml(fileOrUrl,options,function(err,result){
keep = result;
if (result.collection.length<1) {
if (result.version > 1) {
process.exitCode = result.version;
}
else {
process.exitCode = 99;
}
}
for (var o in result.collection) {
valid.push(false);
var api = _.cloneDeep(result.collection[o]);
SwaggerParser.validate(api, function(vErr, api) {
if (vErr) {
console.error(vErr);
}
else {
var masheryId = api.info["x-mashery-id"];
var index = result.ids.indexOf(masheryId);
if (index>=0) {
valid[index] = true;
}
else {
console.log('Could not find API by id: '+masheryId);
}
}
});
}
});
process.on('exit',function(code){
for (var o in keep.collection) {
var api = keep.collection[o];
var dir = './apis/'+api.host;
safeMkdir(dir);
dir += '/' + api.info.title.replace(' API','').split('*').join('').split('?').join('').trim().split(' ').join('-');
safeMkdir(dir);
dir += '/' + api.info.version.split(' ').join('-');
safeMkdir(dir);
try { fs.unlinkSync(dir+'/swagger.json'); } catch (ex) {}
try { fs.unlinkSync(dir+'/swagger.err'); } catch (ex) {}
var extension = '';
if (valid[o]) {
extension = 'json';
}
else {
//console.log('%s %s %s',api.host,api.info.title,api.info.version);
process.exitCode = 1;
fails++;
extension = 'err';
}
console.log('out: '+dir+'/swagger.'+extension);
fs.writeFileSync(dir+'/swagger.'+extension,JSON.stringify(api,null,2),'utf8');
}
if (process.exitCode>0) {
var log = 'Fail '+process.exitCode+' '+fileOrUrl+'\n';
fs.appendFileSync('./mashery2openapi.log',log,'utf8');
}
console.log('Exiting: %s with %s failures',process.exitCode || code,fails);
});