Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
public async init() {
try {
// parse the document
this.document = await SwaggerParser.parse(this.inputDocument);
// validate the document
this.validateDefinition();
// dereference the document into definition
this.definition = await SwaggerParser.dereference(this.document);
} catch (err) {
if (this.strict) {
// in strict-mode, fail hard and re-throw the error
throw err;
} else {
// just emit a warning about the validation errors
console.warn(err);
}
}
async parse(specification) {
let spec, data;
try {
// parse first, to avoid dereferencing of $ref's
data = await swp.parse(specification);
// save the original (with $refs) because swp.validate modifies its input
this.original = JSON.parse(JSON.stringify(data, null, 2));
// and validate
spec = await swp.validate(data);
} catch (e) {
// eslint-disable-next-line
console.log(e.message);
data = {};
spec = {};
}
if (spec.swagger && spec.swagger.indexOf("2.0") === 0) {
const parserV2 = new ParserV2();
return parserV2.parse(spec);
} else if (spec.openapi && spec.openapi.indexOf("3.0") === 0) {
const parserV3 = new ParserV3();
var SwaggerParser = require('swagger-parser');
var jsf = require('./lib/jsfConfig.js');
var requireAllProperties = require('./lib/utils/helpers.js').requireAllProperties;
// grab expected user input
var parser = new ArgumentParser({
addHelp: true,
description: 'Swagger Data Generator generates mock data from Swagger files.',
});
var args;
parser.addArgument(['-y'], { help: 'Always overwrite output file (do not ask to overwrite)', action: 'storeTrue', dest: 'force-yes' });
parser.addArgument(['swagger-input'], { help: 'Input Swagger file' });
parser.addArgument(['json-output'], { help: 'Output file for generated mock data' });
args = parser.parseArgs(process.arguments);
SwaggerParser.parse(args['swagger-input'])
// parse the data and make sure all the properties are required.
// they need to be required so JSF creates mock data for all properties
.then(successfulParse)
.catch(unSuccessfulParse)
// make sure there are not any references in the definitions and create the mock data
.then(dereferencedSuccess);
// *******************************************************
// Helper Functions
// *******************************************************
/**
* successfulParse - Massage data to require all definiton properties then dereference the api
*
async function generateTestFiles() {
const distFolder = path.resolve(process.cwd(), 'dist', 'apis');
if (!existsSync(distFolder) && mkdirSync) {
mkdirSync(distFolder, { recursive: true });
}
const file = await loadSwaggerFile();
const context = await swaggerParser.parse(file);
const paths = Object.keys(context.paths);
const files = new Map();
const templatePath = path.resolve(process.cwd(), 'templates', 'api.hbs');
const template = readFileSync(templatePath).toString();
const compiledTemplate = handlebars.compile(template);
for (let url of paths) {
if (url) {
const names = url.split('/');
let fileName = names.length > 1 ? names[1] : names[0];
fileName = fileName || '_root';
if (!files.has(fileName)) {
files.set(fileName, []);
}
module.exports = function dereference(filename, options, cb) {
var output = [];
output.push(util.format('Dereferencing file: %s', filename));
swagger.parse(filename, {resolveExternal$Refs: options.externalRefs}, function(err, api, metadata) {
//console.log('filename: %s\noptions: %s', filename, JSON.stringify(_.omit(options, 'parent'), null, 2));
if (err) {
return cb(err, output);
}
//Check to see if a file to write the output to was specified, else output to terminal
if (options.outputFile) {
output.push(chalk.green('File parsed successfully'));
output.push(util.format('Writing parsed data to file %s', options.outputFile));
fs.writeFile(options.outputFile, JSON.stringify(metadata), function(err) {
if (err) {
return cb(err, output);
}
output.push(chalk.green('Parsed data successfully written to file'));
cb(null, output);
});
}
it("swagger-parser should be able to parse it without errors", function(done) {
fs.writeFileSync("./spec/swagger.json", JSON.stringify(swaggerJson));
parser.parse("./spec/swagger.json", function(err) {
done(err);
});
});
});
function generateApi (apiProxy, options, cb) {
var destination = options.destination || path.join(__dirname, '../../../api_bundles')
if (destination.substr(-1) === '/') {
destination = destination.substr(0, destination.length - 1)
}
var srcDirectory = destination + '/' + apiProxy + '/apiproxy/'
var destDirectory = destination + '/' + apiProxy + '/apiproxy.zip'
parser.parse(options.source, function (err, api, metadata) {
if (!err) {
console.log('API name: %s, Version: %s', api.info.title, api.info.version)
generateSkeleton(apiProxy, options, function (err, reply) {
if (err) return cb(err)
async.parallel([
function (callback) {
generateProxy(apiProxy, options, api, function (err, reply) {
if (err) return callback(err)
callback(null, 'genProxy')
})
},
function (callback) {
generateProxyEndPoint(apiProxy, options, api, function (err, reply) {
if (err) return callback(err)
callback(null, 'genProxyEndPoint')
})
private async setup() {
await this.getBuiltinPluginsMap();
await this.setupOptions();
SwaggerParser.parse(this.options.api, (err: Error, api: object) => {
if (err) {
throw err;
} else {
this.bootstrap(api);
}
});
}
/**
function buildSchema(swaggerPath, options) {
return Promise.all([
SwaggerParser.dereference(swaggerPath),
SwaggerParser.parse(swaggerPath)
]).then(function ([dereferencedJsonSchema, jsonSchema]) {
return buildValidations(jsonSchema, dereferencedJsonSchema, options);
});
}
exports.createActiveDocs = function(file){
var url = config.get("threescale:API") +"/active_docs.json";
//Parse swagger file and extract info from it
return SwaggerParser.parse(file)
.then(function(api){
var n = Math.floor((Math.random() * 50) + 10);
api.host = 'CHANGEME';
var options ={
method: 'POST',
uri: url,
form:{
"access_token": config.get("threescale:access_token"),
"name": api.info.title,
//"system_name": slug(api.info.title+n),
"system_name": slug(api.info.title),
"body": JSON.stringify(api,null,4),
"description": api.info.description || "Activedocs file description",
"published": true,
"skip_swagger_validations": false
},