translate-api
 1  #!/usr/bin/env node
 2  
 3  var fs = require('fs');
 4  var Translator = require('./lib/translator');
 5  var removeEventStreamOperations = require('./lib/remove-event-stream-ops').removeEventStreamOperations;
 6  var util = require('util');
 7  var path = require('path');
 8  
 9  /*
10   * Minimizes all .normal.json files by flattening shapes, removing
11   * documentation and removing unused shapes. The result will be written to
12   * `.min.json` file.
13   *
14   * The passed parameter is base path. The directory must include the apis/
15   * folder.
16   */
17  function ApiTranslator(basePath) {
18    this._apisPath = path.join(basePath, 'apis');
19  }
20  
21  /*
22   * minimize passed .normal.json filepath into .min.json
23   */
24  ApiTranslator.prototype.minimizeFile = function minimizeFile(filepath) {
25    var opath = filepath.replace(/\.normal\.json$/, '.min.json');
26    var data = JSON.parse(fs.readFileSync(path.join(this._apisPath, filepath)).toString());
27    var didModify = removeEventStreamOperations(data);
28    if (didModify) {
29      // original model modified, replace existing normal.json so docs/ts definitions are accurate
30      fs.writeFileSync(path.join(this._apisPath, filepath), JSON.stringify(data, null, '  '));
31    }
32    var translated = new Translator(data, {documentation: false});
33    var json = JSON.stringify(translated, null, '  ');
34    fs.writeFileSync(path.join(this._apisPath, opath), json);
35  };
36  
37  /*
38   * minimize files in api path. If optional modelName is passed only that model
39   * is minimized otherwise all .normal.json files found.
40   */
41  ApiTranslator.prototype.translateAll = function translateAll(modelName) {
42    var paths = fs.readdirSync(this._apisPath);
43    var self = this;
44    paths.forEach(function(filepath) {
45      if (filepath.endsWith('.normal.json')) {
46        if (!modelName || filepath.startsWith(modelName)) {
47          self.minimizeFile(filepath);
48        }
49      }
50    });
51  };
52  
53  /*
54   * if executed as script initialize the ApiTranslator and minimize API files
55   *
56   * Optional first parameter specifies which model to minimize. If omitted all
57   * files are selected.
58   *
59   * Optional second parameter specifies base path. The directory must include
60   * the apis/ folder with .normal.json files. Output is written into the same
61   * path. If parameter is not passed the repository root will be used.
62   */
63  if (require.main === module) {
64    var modelName = process.argv[2] || '';
65    var basePath = process.argv[3] || path.join(__dirname, '..');
66    new ApiTranslator(basePath).translateAll(modelName);
67  }
68  
69  module.exports = ApiTranslator;