Coder Social home page Coder Social logo

mikestead / swagger-routes Goto Github PK

View Code? Open in Web Editor NEW
20.0 6.0 8.0 242 KB

Generate Express or Restify route handlers from a Swagger specification

License: MIT License

JavaScript 99.20% HTML 0.80%
swagger openapi rest restify route-handlers express

swagger-routes's People

Contributors

g-junming avatar jamidon avatar laszlo-vadasz-deltatre avatar mike-stead-deltatre avatar mikestead avatar mtribes-sdk-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

swagger-routes's Issues

path.id is not of a type(s) integer

Am getting a validation error path.id is not of a type(s) integer whenever I use a path value that contains an integer. Must all path values be defined as strings?

/artist/{id}:
  x-serviceId: 'artist'
  get:
    tags:
    - "event"
    summary: "getArtist"
    description: "Get an artist by ID"
    produces:
    - "application/json"
    parameters:
    - name: "id"
      in: "path"
      description: "artist identifier"
      required: true
      type: "integer"
      format: "int64"

Help on usage

Hi, really liking this library too, been looking for something to allow me to do some specific route handling in node express from a swagger file.

Use case: add the tag name to the route handler
It looks like the handlerfactory approach would work well for this, but the examples are a little above my understanding. Could you help me work out what a handler might look like for this case?

api.yaml: parameters and other stuff omitted for brevity

  /authtest/{id}:
    get:
      x-method-id: "1022"
      tags:
      - "system"
  post:
      x-method-id: "1023"
      tags:
      - "system"

required handler folder structure for both of these would be

/routes/system/authtest,js

methods in that handler would be

authtestPOST(req, res, next)
authtestGET(req, res, next)

And the x-method-id needs to be parsed and available in the request somewhere.

Support for restify 7.x and 8.x

We are using this library for all routes on Restify 4.x and 6.x without issues. There is however change in path resolver in restify 7.x and it is causing this issue:

Generated 'api.yml'
13:44:51.878Z FATAL rocket: Uncaught exception, aborting Node (err.code=ERR_ASSERTION)
    AssertionError [ERR_ASSERTION]: The first character of a path should be `/` or `*`
        at Router.on (...\node_modules\find-my-way\index.js:69:3)
        at RouterRegistryRadix.add (...\node_modules\restify\lib\routerRegistryRadix.js:42:21)
        at Router.mount (...\node_modules\restify\lib\router.js:212:20)
        at Server.serverMethod [as get] (...\node_modules\restify\lib\server.js:1686:33)
        at registerDocsRoute (...\node_modules\swagger-routes\src\routeRegister.js:36:7)
        at Object.registerRoutes (...\node_modules\swagger-routes\src\routeRegister.js:12:3)
        at addHandlers (...\node_modules\swagger-routes\src\index.js:19:17)

It happens ^^ when we call swaggerRoutes(server, {

To see what exactly is happening I logged data from https://github.com/mikestead/swagger-routes/blob/master/src/routeRegister.js#L34

And if I update it with this:

function registerDocsRoute(app, options) {
  console.log(`/${options.api.basePath}/${options.docsPath}`)
  const docsPath = path.normalize(`/${options.api.basePath}/${options.docsPath}`)
  console.log(docsPath);
  app.get(docsPath, options.docsMiddleware, function handler(req, res) { res.json(options.api) })
}

Then this is logged before error:

////spec
\spec

For new restify resolver, path cannot start with \.

When I tried to just comment this line https://github.com/mikestead/swagger-routes/blob/master/src/routeRegister.js#L36 then everything else is working correctly and it loads all paths same as before.

Removing an API, adding an API using JSON and preventing handler generation.

Hi, I'm trying out the library. Really great work.

I'm going through the code now but have a few questions:

  1. Is there a way to dynamically remove an API from a running server (using restify in my case)?
  2. Is there a recommended way to pass a json swagger object instead of yaml?
  3. Is there a way to prevent handler generation completely?

Thank you!

Unexpected fields validation

Currently swagger-routes silently accepts unsupported fields. It would be useful to be able to enable enforcement of only defined fields to be present.

formData required validation

Greetings everyone,
I'm having problem when validation formData file upload with multer and swaggerRoutes.
swagger.yml

parameters:
- in: "formData"
        type: "file"
        required: true
        name: "document"

The swaggerRoutes method returns this when validating the "required: true":
"message": "formData requires property \"document\""

If I set required as false, the swaggerRotues continues without any problem.

Anyone have any ideas how to solve this?

`apiSpecs.js` broken after axios update

#22 updated axios from 0.9.1 to 0.18.1

Release 0.13.0 of axios contains a breaking change with error formats - errors are now errors rather than response objects. This is not handled by the apiSpecs.js code and we get failures in various places.

I will have a look at fixing this and opening a PR if I get a chance

Not initializing on Windows

Tried to initialize like this using a basic swagger json on Windows:
swaggerRoutes(server, { api: './definitions/openapi.json', handlers: { path: './dist/handlers/v1', template: './definitions/template/handler.mustache', getTemplateView: (operation) => operation,template generate: enableCodeGenerator, group: false, }, authorizers: './src/security/v1', });

However, getting error:

AssertionError [ERR_ASSERTION]: The first character of a path should be / or *

After doing some investigation found that this is caused by line 35 on routerRegister.js file

Changed path.normalize to path.posix.normalize and it fixed the issue.

Array items failing validation

yaml definition

testarray:
  type: "array"
  items:
    type: "integer"
    format: "int64"

sending this data in the body:

testarray: [1,5,9]

-or-

testarray: 1,5,9

returns this error:

body.testarray[0] is not of a type(s) integer, body.testarray[1] is not of a type(s) integer, body.testarray[2] is not of a type(s) integer

Of course, it may well be the format I am sending...

Errors from middleware swallowed by promise

The authorisation middleware that is added by this module here looks like this:

function authorize(req, res, next) {
    return Promise.all(...)
    .then(() => next())
    .catch(e => next(e))
  }

This causes errors that are thrown from middleware further down the chain to be swallowed due to this: restify/node-restify/issues/962

Essentially the .then(() => next()) means that the execution carries on inside the promise scope, so any errors then thrown will land in .catch(e => next(e)), but by this time the next function has already been called once and calling it again has no effect.

Resolving this I think means removing the promises or potentially something like:

function authorize(req, res, next) {
    return Promise.all(...)
    .then(() => setImmediate(next))
    .catch(e => next(e))
  }

Response validation

Currently swagger-routes only supports validating request structure; would be extremely useful if it could validate responses as well.

Order of excecution of security handlers

Is there a way to run the security handlers sequentially? I have two handlers A and B where B depends on A but due to the handlers being executed in parallel, that dependency can not be enforced. I looked through the docs but I could not find a flag that allows one to achieve that.

Split apiSpecs into separate module

At the moment the src/apiSpecs file is intended for testing only, yet it accounts for almost all of the dependencies of this module.

The upshot is we are pulling in modules like expect which has a shed load of its own dependencies into our production builds.

Ideally we could split the apiSpecs out somehow so this is not the case. Cant think of a really elegant solution but some ideas:

  1. Set the dependencies only needed for this file as optionalDependencies - then consumers can chose not to install. Don't really like this one as I don't know how other modules would use optional dependencies
  2. Move apiSpecs into a subdirectory with its own package.json - then somehow just do a local install on this dir if needed
  3. Move apiSpecs into a totally separate repo - bit of a hassle

Parameter with an array is not being validated and maybe not parsed correctly

I'm trying to track down a problem with passing arrays to some of my POST methods where validation isn't happening. I've attached part of a Swagger 2.0 schema JSON file: api.txt that illustrates the problem. I did verify that it is valid by checking it against Swagger 2.0 Parser.

The swagger-ui looks like this:
swagger-ui

As you can see, the page doesn't seem to know an array of values can be sent to the organizations/add interface. Also, if I pass something invalid like:

{ "name": "foo", "abbreviation": "bar" }

which is not an array or

[ { "name21": "foo", "abbreviation": "bar" } ]

where name21 is invalid.

My little bootstrap for hosting this is:

const swaggerRoutes = require('swagger-routes');
const restify = require('restify');

const server = restify.createServer();
server.use(restify.acceptParser(server.acceptable));
server.use(restify.authorizationParser());
server.use(restify.dateParser());
server.use(restify.queryParser({ mapParams: false }));
server.use(restify.jsonp());
server.use(restify.gzipResponse());
server.use(restify.bodyParser());
server.use(restify.CORS());
server.use(restify.fullResponse());

function createHandler(operation) {
  return function handler(req, res, next) {
    res.send(operation.id);
  };
}

swaggerRoutes(server, {
  api: './api.json',
  handlers: createHandler
});
server.listen(8080);

Any idea as to where to look to track this down?

Thanks.

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.