Coder Social home page Coder Social logo

0xthk / swagger2 Goto Github PK

View Code? Open in Web Editor NEW

This project forked from carlansley/swagger2

0.0 0.0 0.0 322 KB

Loading, parsing and validating requests to HTTP services based on Swagger v2.0 documents

License: MIT License

JavaScript 0.59% TypeScript 99.41%

swagger2's Introduction

Build Status Coverage Status Dependencies Known Vulnerabilities

swagger2

Loading, parsing and validating requests to HTTP services based on Swagger v2.0 documents.

Benefits

  • Fast. Pre-compiled regular expressions and code generation used to validate the inputs and outputs of Swagger 2.0 operations at run-time.
  • Typed. swagger2 is implemented in TypeScript 2, including a fully annotated TypeScript definition of the Swagger 2.0 document object. Makes working with Swagger objects more pleasant in the IDE of your choosing (WebStorm, Atom, etc).

Installation

$ npm install swagger2 --save

Usage

Basic loading and validation of swagger 2.0 document:

import * as swagger from 'swagger2';

// load YAML swagger file
const document = swagger.loadDocumentSync('./swagger.yml');

// validate document
if (!swagger.validateDocument(document)) {
  throw Error(`./swagger.yml does not conform to the Swagger 2.0 schema`);
}

You can compile the document for fast validation of operation requests and responses within the framework of your choosing. Koa 2 example:

let app = new Koa();

...
app.use(body());
app.use(createKoaMiddleware(document));
...


function createKoaMiddleware(document: swagger.Document) {

  // construct a validation object, pre-compiling all schema and regex required
  let compiled = swagger.compileDocument(document);

  return async(context, next) => {

    if (!context.path.startsWith(document.basePath)) {
      // not a path that we care about
      await next();
      return;
    }

    let compiledPath = compiled(context.path);
    if (compiledPath === undefined) {
      // if there is no single matching path, return 404 (not found)
      context.status = 404;
      return;
    }

    // check the request matches the swagger schema
    let validationErrors = swagger.validateRequest(compiledPath,
      context.method, context.request.query, context.request.body);
    if (validationErrors === undefined) {
      // operation not defined, return 405 (method not allowed)
      context.status = 405;
      return;
    }

    if (validationErrors.length > 0) {
      context.status = 400;
      context.body = {
        code: 'SWAGGER_REQUEST_VALIDATION_FAILED',
        errors: validationErrors
      };
      return;
    }

    // wait for the operation to execute
    await next();

    // check the response matches the swagger schema
    let error = swagger.validateResponse(compiledPath, context.method, context.status, context.body);
    if (error) {
      error.where = 'response';
      context.status = 500;
      context.body = {
        code: 'SWAGGER_RESPONSE_VALIDATION_FAILED',
        errors: [error]
      };
    }
  };
}


There is a complete implementation of this example/use-case in the swagger2-koa module, so if you're using Koa 2 it may make sense to use that instead of swagger2 directly.

Limitations

  • currently only supports synchronous loading of full documents (via swagger.loadDocumentSync)
  • does not support validation of file attachments
  • does not support validation of mime-types
  • requires node v6.0 or above

Development

First, grab the source from GitHub.

From within the swagger2 directory, to run tests:

$ npm install
$ npm test

To see code coverage in a web-browser:

$ npm run cover:browser

To clean up:

$ npm run clean

License

MIT

swagger2's People

Contributors

0xthk avatar adcreare avatar bbeeler-flowhub avatar brad-jones avatar carlansley avatar cholzberger avatar ctc316 avatar shaxbee avatar supertong avatar zaaack avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.