diff --git a/bin/swagger-jsdoc.js b/bin/swagger-jsdoc.js index 339b125a..9a44a425 100755 --- a/bin/swagger-jsdoc.js +++ b/bin/swagger-jsdoc.js @@ -1,6 +1,7 @@ #!/usr/bin/env node const fs = require('fs'); +const path = require('path'); const program = require('commander'); const pkg = require('../package.json'); @@ -76,6 +77,7 @@ fs.writeFileSync( swaggerJsdoc({ swaggerDefinition, apis: program.args, + format: path.extname(output || ''), }), null, 2 diff --git a/src/lib.js b/src/lib.js index ee428862..8098870f 100644 --- a/src/lib.js +++ b/src/lib.js @@ -4,6 +4,7 @@ const { build } = require('./specification'); * Generates the specification. * @param {object} options - Configuration options * @param {string} options.encoding Optional, passed to readFileSync options. Defaults to 'utf8'. + * @param {string} options.format Optional, defaults to '.json' - target file format '.yml' or '.yaml'. * @param {object} options.swaggerDefinition * @param {object} options.definition * @param {array} options.apis diff --git a/src/specification.js b/src/specification.js index f58d3821..eb8f4648 100644 --- a/src/specification.js +++ b/src/specification.js @@ -55,6 +55,17 @@ function prepare(definition) { return swaggerObject; } +/** + * @param {object} obj + * @param {string} ext + */ +function format(swaggerObject, ext) { + if (ext === '.yml' || ext === '.yaml') { + return YAML.stringify(swaggerObject); + } + return swaggerObject; +} + /** * OpenAPI specification validator does not accept empty values for a few properties. * Solves validator error: "Schema error should NOT have additional properties" @@ -82,7 +93,7 @@ function clean(swaggerObject) { * @param {object} swaggerObject - Swagger object from parsing the api files. * @returns {object} The specification. */ -function finalize(swaggerObject) { +function finalize(swaggerObject, options) { let specification = swaggerObject; parser.parse(swaggerObject, (err, api) => { @@ -95,7 +106,7 @@ function finalize(swaggerObject) { specification = clean(specification); } - return specification; + return format(specification, options.format); } /** @@ -265,7 +276,7 @@ function build(options) { } } - return finalize(specification); + return finalize(specification, options); } -module.exports = { prepare, build, organize, finalize }; +module.exports = { prepare, build, organize, finalize, format }; diff --git a/test/specification.spec.js b/test/specification.spec.js index 25ad64fa..148881e2 100644 --- a/test/specification.spec.js +++ b/test/specification.spec.js @@ -95,4 +95,15 @@ describe('Specification module', () => { }); }); }); + + describe('format', () => { + it('should not modify input object when no format specified', () => { + expect(specModule.format({ foo: 'bar' })).toEqual({ foo: 'bar' }); + }); + + it('should support yaml', () => { + expect(specModule.format({ foo: 'bar' }, '.yaml')).toEqual('foo: bar\n'); + expect(specModule.format({ foo: 'bar' }, '.yml')).toEqual('foo: bar\n'); + }); + }); });