var yaml = require('js-yaml'), fs = require('fs'); module.exports = { asJson: function(spec) { try { return JSON.parse(spec); } catch (jsonException) { throw new SyntaxError(`Specification is not a valid JSON. ${jsonException}`); } }, asYaml: function(spec) { try { return yaml.safeLoad(spec); } catch (yamlException) { throw new SyntaxError(`Specification is not a valid YAML. ${yamlException}`); } }, validateSpec: function(spec) { // Checking for the all the required properties in the specification if (!spec.hasOwnProperty('openapi')) { return { result: false, reason: 'Specification must contain a semantic version number of the OAS specification' }; } if (!spec.paths) { return { result: false, reason: 'Specification must contain Paths Object for the available operational paths' }; } if (!spec.hasOwnProperty('info')) { return { result: false, reason: 'Specification must contain an Info Object for the meta-data of the API' }; } if (!spec.info.hasOwnProperty('title')) { return { result: false, reason: 'Specification must contain a title in order to generate a collection' }; } if (!spec.info.hasOwnProperty('version')) { return { result: false, reason: 'Specification must contain a semantic version number of the API in the Info Object' }; } // Valid specification return { result: true, openapi: spec }; }, validateRoot: function(spec) { // Checking for the all the required properties needed in a root file if (!spec.hasOwnProperty('openapi')) { return { result: false, reason: 'Specification must contain a semantic version number of the OAS specification' }; } if (!spec.paths) { return { result: false, reason: 'Specification must contain Paths Object for the available operational paths' }; } if (!spec.hasOwnProperty('info')) { return { result: false, reason: 'Specification must contain an Info Object for the meta-data of the API' }; } // Valid specification return { result: true, openapi: spec }; }, getOasObject: function(file) { let oasObj = file; if (typeof file === 'string') { try { oasObj = JSON.parse(file); } catch (jsonEx) { // Not direct JSON. Could be YAML try { oasObj = yaml.safeLoad(file); } catch (yamlEx) { // Not JSON or YAML return { result: false, reason: 'The input must be valid JSON or YAML' }; } // valid YAML } } return oasObj; }, getRootFiles: function(filesPathArray) { let rootFilesArray = []; filesPathArray.forEach((filePath) => { let file = fs.readFileSync(filePath.fileName, 'utf8'), oasObject = this.getOasObject(file); if (this.validateRoot(oasObject).result) { rootFilesArray.push(filePath.fileName); } }); return rootFilesArray; } };