translate-api 2.5 KB

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