How to use swagger-parser - 10 common examples

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 egovernments / egov-services / web / spec-directory / server.js View on Github external
] = {};
            uniqueKeyObj[allModule.toLowerCase()][allMaster.toLowerCase()] =
              allModuleData[allModule][allMaster].uniqueKeys;
          }
        }
      }
      // console.log(uniqueKeyObj);
    }
  }
);

// console.log(specificHeaderObj);

// for(module in modules){
for (var i = 0; i < urls.length; i++) {
  SwaggerParser.dereference(urls[i])
    .then(function(yamlJSON) {
      // console.log(yamlJSON)
      let module = yamlJSON["x-module"];
      if (module) {
        mainObj[module] = yamlJSON.definitions;
      } else {
        let basePath = [];
        basePath = yamlJSON.basePath.split("-")[0].split(""); // "/asset-services" type pattern should be in basepath
        let index = basePath.indexOf("/");
        if (index > -1) {
          basePath.splice(index, 1);
        }

        mainObj[basePath.join("")] = yamlJSON.definitions;
      }
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);
      }
    }

    // build schemas for all operations
    const operations = this.getOperations();
    operations.map(this.buildSchemaForOperation.bind(this));

    // now that the definition is loaded and dereferenced, we are initalized
    this.initalized = true;
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 Testlio / lambda-tools / bin / lambda-run.js View on Github external
promise.then(function() {
        swagger.validate(apiFile, function(err, api) {
            if (err) {
                console.error(chalk.red('Failed to start server'), err.message);
                console.error(err.stack);
                return;
            }

            const router = koaRouter();

            // For each of the paths in the API, we want to set up a route that handles it
            _.forEach(api.paths, function(methods, apiPath) {
                _.forEach(methods, function(definition, method) {
                    // Convert path to be koa-router suitable (variables are listed differently)
                    const parsedPath = apiPath.replace(/\{([^\}\/]*)\}/g, ':$1');

                    // Set up the route for the path
                    router[method](parsedPath, Route(_.get(definition, 'x-amazon-apigateway-integration'), program));
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 teamdigitale / io-functions / api / generate_models.ts View on Github external
async function generateApi(
  e: nunjucks.Environment,
  specFileName: string,
  root: string
): Promise<void> {
  const api: Spec = await SwaggerParser.bundle(`api/${specFileName}.yaml`);

  const specCode = `
    /* tslint:disable:object-literal-sort-keys */
    /* tslint:disable:no-duplicate-string */

    // DO NOT EDIT
    // auto-generated by generated_model.ts from ${specFileName}.yaml

    export const specs = ${JSON.stringify(api)};
  `;
  await fs.writeFile(
    `${root}/${specFileName}.ts`,
    prettier.format(specCode, {
      parser: "typescript"
    })
  );
github BlueOakJS / blueoak-server / services / swagger.js View on Github external
async.eachSeries(files, function parseSwagger(file, swagCallback) {
        var handlerName = path.basename(file); //use the swagger filename as our handler module id
        handlerName = handlerName.substring(0, handlerName.lastIndexOf('.')); //strip extensions

        var derefPromise = parser.validate(file);
        parser.bundle(file)
            .then(function (bundledApi) {
                specs.bundled[handlerName] = bundledApi;
                return derefPromise;
            })
            .then(function (dereferencedApi) {
                specs.dereferenced[handlerName] = dereferencedApi;
                if (polymorphicValidation !== 'off') {
                    preparePathsForPolymorphicValidation(dereferencedApi.paths, responseModelValidationLevel);
                }
                prepareDefinitionsForPolymorphicValidation(dereferencedApi.definitions);
                specs.names.push(handlerName);
                return swagCallback();
            })
            .catch(function (error) {
                // don't generate an error if it was a non-Swagger Spec JSON file
                var swagErr = error;
github EricHenry / swagger-data-gen / src / sdg.js View on Github external
run(config = {}) {
    let configFormatters = (config.formatters ? config.formatters : DEFAULT_RUN_CONFIG.formatters);
    let configMiddleware = (config.middleware ? config.middleware : DEFAULT_RUN_CONFIG.middleware);

    // apply any registered formatters
    this._formatters = configure(this._formatters, configFormatters);
    this._formatters.forEach(({ formatName, callback }) => jsf.format(formatName, callback));

    return SwaggerParser.bundle(this._pathToFile)
      .then(api => {
        this._middleware = configure(this._middleware, configMiddleware);

        let modifiedApi = Object.assign({}, api);
        this._middleware.forEach(func => modifiedApi = func(modifiedApi));
        return modifiedApi;
      })
      .then(api => SwaggerParser.dereference(api))
      .then(api => this._parsedFile = api)
      .catch((err) => { throw new Error(`Error has occured when trying to bundle and dereference the OpenAPI / Swagger object. \n Error: ${err}`); });
  }
github EricHenry / swagger-data-gen / src / SwaggerDataGen.ts View on Github external
export function build(swaggerSchema: string | Swagger, config: BuildOptions = {}): Promise<Swagger> {
  const { formatters, middleware } = config;
  const configurationF = (formatters ? formatters : DEFAULT_CONFIG_FORMATTER);
  const configurationM = (middleware ? middleware : DEFAULT_CONFIG_MIDDLEWARE);

  // create a registered array of formatters based on the configuration
  const _formatters = configure(CORE_FORMATTERS, configurationF);

  // apply any registered formatters
  _formatters.forEach(({ formatName, callback }) => jsf.format(formatName, callback));

  return SwaggerParser.bundle(swaggerSchema)
    .then((api: Swagger) => {
      // create a registered array of middleware based on the configuration
      const _middleware = configure(CORE_MIDDLEWARE, configurationM);
      let modifiedApi = Object.assign({}, api);

      //apply any registered middleware
      _middleware.forEach(m => modifiedApi = m(modifiedApi));
      return modifiedApi;
    })
    .then((api: Swagger) => SwaggerParser.dereference(api))
    .catch((err: Error) => {
      throw new Error(`Error has occured when trying to bundle and dereference the OpenAPI / Swagger object. \n Error: ${err}`);
    });
}

swagger-parser

Swagger 2.0 and OpenAPI 3.0 parser and validator for Node and browsers

MIT
Latest version published 1 year ago

Package Health Score

79 / 100
Full package analysis