swagger-jsdoc.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #!/usr/bin/env node
  2. const fs = require('fs');
  3. const path = require('path');
  4. const program = require('commander');
  5. const pkg = require('../package.json');
  6. const swaggerJsdoc = require('..');
  7. const { loadDefinition } = require('../src/utils');
  8. program
  9. .version(pkg.version)
  10. .usage('[options] <path ...>')
  11. .option(
  12. '-d, --definition <swaggerDefinition.js>',
  13. 'Input swagger definition.'
  14. )
  15. .option('-o, --output [swaggerSpec.json]', 'Output swagger specification.')
  16. .parse(process.argv);
  17. if (!process.argv.slice(2).length) {
  18. program.help();
  19. process.exit();
  20. }
  21. const { definition } = program;
  22. const output = program.output || 'swagger.json';
  23. if (!definition) {
  24. console.log('Definition file is required.');
  25. program.help();
  26. process.exit();
  27. }
  28. let swaggerDefinition;
  29. try {
  30. swaggerDefinition = loadDefinition(
  31. definition,
  32. fs.readFileSync(definition, 'utf-8')
  33. );
  34. } catch (error) {
  35. console.log(
  36. `Error while loading definition file '${definition}':\n${error.message}`
  37. );
  38. process.exit();
  39. }
  40. // Check for info object in the definition.
  41. if (!('info' in swaggerDefinition)) {
  42. console.log('Definition file should contain an info object!');
  43. console.log('More at http://swagger.io/specification/#infoObject');
  44. process.exit();
  45. }
  46. // Check for title and version properties in the info object.
  47. if (
  48. !('title' in swaggerDefinition.info) ||
  49. !('version' in swaggerDefinition.info)
  50. ) {
  51. console.log('The title and version properties are required!');
  52. console.log('More at http://swagger.io/specification/#infoObject');
  53. process.exit();
  54. }
  55. // Continue only if arguments provided.
  56. if (!program.args.length) {
  57. console.log('You must provide sources for reading API files.');
  58. process.exit();
  59. }
  60. const format = path.extname(output);
  61. const result = swaggerJsdoc({
  62. swaggerDefinition,
  63. apis: program.args,
  64. format,
  65. });
  66. if (format === '.json') {
  67. fs.writeFileSync(output, JSON.stringify(result, null, 2));
  68. } else {
  69. fs.writeFileSync(output, result);
  70. }
  71. console.log('Swagger specification is ready.');