How to use the swagger-parser.parse function in swagger-parser

To help you get started, we’ve selected a few swagger-parser examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github anttiviljami / openapi-backend / src / backend.ts View on Github external
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);
      }
    }
github seriousme / fastify-openapi-glue / lib / parser.js View on Github external
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();
github EricHenry / swagger-data-gen / index.js View on Github external
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
 *
github vellengs / nestx / packages / servers / nest-testing / scripts / generate.ts View on Github external
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, []);
            }
github APIDevTools / swagger-cli / lib / dereference.js View on Github external
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);
      });
    }
github CleverCloud / wadl2json / spec / wadl2json.spec.js View on Github external
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);
    });
  });
});
github anil614sagar / openapi2apigee / lib / commands / generateApi / generateApi.js View on Github external
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')
            })
github mean-expert-official / openapi-sdk-builder / src / core / osb.ts View on Github external
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);
      }
    });
  }
  /**
github Zooz / api-schema-builder / src / index.js View on Github external
function buildSchema(swaggerPath, options) {
    return Promise.all([
        SwaggerParser.dereference(swaggerPath),
        SwaggerParser.parse(swaggerPath)
    ]).then(function ([dereferencedJsonSchema, jsonSchema]) {
        return buildValidations(jsonSchema, dereferencedJsonSchema, options);
    });
}
github pszuster / 3ScaleTD / 3scale-Swagger-Import / lib / activedocs.js View on Github external
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
      },