translate-api
2.4 KB
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
#!/usr/bin/env node
var fs = require('fs');
var Translator = require('./lib/translator');
var removeEventStreamOperations = require('./lib/remove-event-stream-ops').removeEventStreamOperations;
var util = require('util');
var path = require('path');
/*
* Minimizes all .normal.json files by flattening shapes, removing
* documentation and removing unused shapes. The result will be written to
* `.min.json` file.
*
* The passed parameter is base path. The directory must include the apis/
* folder.
*/
function ApiTranslator(basePath) {
this._apisPath = path.join(basePath, 'apis');
}
/*
* minimize passed .normal.json filepath into .min.json
*/
ApiTranslator.prototype.minimizeFile = function minimizeFile(filepath) {
var opath = filepath.replace(/\.normal\.json$/, '.min.json');
var data = JSON.parse(fs.readFileSync(path.join(this._apisPath, filepath)).toString());
var didModify = removeEventStreamOperations(data);
if (didModify) {
// original model modified, replace existing normal.json so docs/ts definitions are accurate
fs.writeFileSync(path.join(this._apisPath, filepath), JSON.stringify(data, null, ' '));
}
var translated = new Translator(data, {documentation: false});
var json = JSON.stringify(translated, null, ' ');
fs.writeFileSync(path.join(this._apisPath, opath), json);
};
/*
* minimize files in api path. If optional modelName is passed only that model
* is minimized otherwise all .normal.json files found.
*/
ApiTranslator.prototype.translateAll = function translateAll(modelName) {
var paths = fs.readdirSync(this._apisPath);
var self = this;
paths.forEach(function(filepath) {
if (filepath.endsWith('.normal.json')) {
if (!modelName || filepath.startsWith(modelName)) {
self.minimizeFile(filepath);
}
}
});
};
/*
* if executed as script initialize the ApiTranslator and minimize API files
*
* Optional first parameter specifies which model to minimize. If omitted all
* files are selected.
*
* Optional second parameter specifies base path. The directory must include
* the apis/ folder with .normal.json files. Output is written into the same
* path. If parameter is not passed the repository root will be used.
*/
if (require.main === module) {
var modelName = process.argv[2] || '';
var basePath = process.argv[3] || path.join(__dirname, '..');
new ApiTranslator(basePath).translateAll(modelName);
}
module.exports = ApiTranslator;