How to use the swagger-parser.validate 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 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 APIs-guru / unofficial_openapi_specs / testRunner.js View on Github external
if (name.indexOf('.yaml')>=0) {
				src = yaml.safeLoad(srcStr);
			}
			else {
				src = JSON.parse(srcStr);
			}
		}
		catch (ex) {
			var warning = 'Could not parse file '+file;
			console.log(red+warning);
			warnings.push(warning);
		}

		//if (!src || ((!src.swagger && !src.openapi))) return true;

        if (src) validator.validate(src,function(err,api){
		    if (!argv.quiet) console.log(normal+file);
			if (err) {
				if (argv.quiet) console.log(normal+file);
				console.log(red+options.context.pop()+'\n'+util.inspect(err));
				result = false;
				failures.push(file);
			}
			else {
				if (!argv.quiet) {
		  			console.log(green+'%s %s',src.info.title,src.info.version);
					console.log('  %s',src.swagger ? (src.host ? src.host : 'relative') : (src.servers && src.servers.length ? src.servers[0].url : 'relative'));
				}
				result = true;
			}
			if (expectFailure) result = !result;
			if (result) {
github subeeshcbabu / swagmock / tests / responses_mockgen.js View on Github external
describe('Responses Mock generator', () => {
    let apiPath = Path.resolve(__dirname, 'fixture/petstore.json');
    let apiResolver = Parser.validate(apiPath);
    let swagmock = Swagmock(apiResolver, { validated: true });

    it('should generate response mock for path /store/order/{orderId}, get operation', (done) => {
        let mockgen = swagmock.responses({
            path: '/store/order/{orderId}',
            operation: 'get'
        });
        mockgen.then(mock => {
            Assert.ok(mock, 'Generated mock');
            let resp = mock.responses;
            Assert.ok(resp, 'Generated response');
            Assert.ok(resp.hasOwnProperty('200'), 'Generated 200 response');
            Assert.ok(resp.hasOwnProperty('400'), 'Generated 400 response');
            Assert.ok(resp.hasOwnProperty('404'), 'Generated 404 response');
            let successResp = resp['200'];
            Assert.ok(Number.isInteger(successResp.id), 'id is integer');
github DataFire / DataFire / test / project.js View on Github external
it('should produce OpenAPI JSON', (done) => {
    swaggerParser.validate(project.openapi, (err, api) => {
      if (process.env.WRITE_GOLDEN) {
        fs.writeFileSync(__dirname + '/golden.openapi.json', JSON.stringify(api || project.openapi, null, 2));
        expect(err).to.equal(null);
      } else {
        expect(err).to.equal(null);
        expect(api).to.deep.equal(require('./golden.openapi.json'));
      }
      done();
    })
  })
})
github quipucords / quipucords / client / scripts / swagger.js View on Github external
app.listen(port, () => {
  console.log(`\nYou can now view API docs in the browser.\n  Open: http://localhost:${port}/docs/api\n`);

  swaggerParser.validate(yamlFile, err => {
    if (err) {
      console.error(`  \x1b[31m${err.name}\n  \x1b[31m${err.message}\x1b[0m\n`);
    }
  });
});
github sky-uk / api-explorer / packages / apiexplorer / src / infrastructure / loaders / openAPI3Loader.js View on Github external
export function openAPI3Loader (config, { onLoadProgress, onNewAPI, onNewOperation, onNewDefinition, onLoadCompleted, onLoadError }) {
  const url = config.url.getUrl()
  onLoadProgress(`Loading API Spec from ${url}`)

  return SwaggerParser.validate(url)
    .then(api => {
      let newApi = api
      let defaultHost = `${window.location.origin}/${config.basePath}`
      newApi = config.interceptor({ friendlyName: config.friendlyName, url: config.url }, api)
      openAPI3SpecLoader(newApi, config.friendlyName, config.slug, defaultHost, { onLoadProgress, onNewAPI, onNewOperation, onLoadCompleted, onLoadError })
    })
    .catch(function (err) {
      onLoadError(err)
    })
}
github wireapp / wire-web-packages / packages / swaxios / src / Swaxios.ts View on Github external
private async validateConfig(swaggerJson: Spec): Promise<void> {
    const clone = JSON.parse(JSON.stringify(swaggerJson));
    await SwaggerParser.validate(clone);
  }
github krakenjs / hapi-openapi / lib / index.js View on Github external
const register = async function (server, options, next) {

    const validation = Joi.validate(options, optionsSchema);

    Hoek.assert(!validation.error, validation.error);

    const { api, cors, vhost, handlers, extensions, outputvalidation } = validation.value;
    let { docs, docspath } = validation.value;
    const spec = await Parser.validate(api);

    spec.basePath = Utils.unsuffix(Utils.prefix(spec.basePath || '/', '/'), '/');

    //Expose plugin api
    server.expose({
        getApi() {
            return spec;
        },
        setHost: function setHost(host) {
            spec.host = host;
        }
    });

    let basedir;
    let apiDocument;
github amazing-gao / koa-oai-router / src / spec.js View on Github external
function parse(apiDir) {
  return swaggerParser.validate(apiDir, { validate: { schema: true, spec: true } })
    .then((api) => {
      return api;
    });
}
github Mermade / check_api / index.js View on Github external
var apib2swagger = require('apib2swagger');
          apib2swagger.convert(api, function (err, res) {
              options.converted = res.swagger;
              callback(err, options);
          });
          }
      else {
          options.message = 'Valid API Blueprint';
                callback(null, options);
      }
      }
  });
}
else if (options.format === 'swagger_2') {
  var orig = api;
  bsc.validate(options.source,{resolve:{external:true},dereference:{circular:'ignore'}},function(err,api){
    if (api && (!api.info || !api.info.title)) {
        err = {error:'No title'};
    }
    if (err) {
        options.message = 'Invalid swagger 2.0';
    }
    else {
        options.message = 'Valid swagger 2.0';
    options.context = [api.info.title+' '+api.info.version+
        ' host:'+(api.host ? api.host : 'relative')];
        if (api.info["x-logo"] && api.info["x-logo"].url) {
            options.context[0] += '\nHas logo: '+api.info["x-logo"].url;
        }
    }
    options.api = api||orig;
    callback(err, options);