swagger2-koa
Koa 2 async-style middleware for loading, parsing and validating requests via swagger2, and serving UI via swagger-ui.
router(document) => koa2-style Router
validate(document) => koa2 middleware
ui(document) => koa2 middleware
Installation
$ npm install swagger2-koa --save
Usage
router(document) => koa2-style Router
This is the easiest way to use swagger2-koa; it creates a standalone koa server, adds the validate
middleware, and returns a
Router object that allows you to add your route implementations.
;; ...const document = swagger;const router: Router = ; router; ... router // get the koa 2 server // only needed if you want to publish a swagger-ui for the API ; // start handling requests on port 3000
Note: in addition to validate
(described below), router
adds the following middleware to its koa server:
koa-cors
koa-router
koa-convert
koa-body
validate(document) => koa2 middleware
If you already have a Koa server, this middleware adds basic loading and validation of HTTP requests and responses against swagger 2.0 document:
;; const app = ; // load YAML swagger fileconst document = swagger; // validate documentif !swagger throw Error`./swagger.yml does not conform to the Swagger 2.0 schema`; app;app;
The validate
middleware behaves as follows:
- expects context.body to contain request body in object form (e.g. via use of koa-body)
- if the request is for a path not defined in swagger document, an HTTP 404 is returned to the client (subsequent middleware is never processed).
- if the request body does not validate, an HTTP 400 is returned to the client (subsequent middleware is never processed)
- if the response body does not validate, an HTTP 500 is returned to the client
For either request (HTTP 400) or response (HTTP 500) errors, details of the schema validation error are passed back in the body. e.g.:
{ "code": "SWAGGER_RESPONSE_VALIDATION_FAILED", "errors": [{ "actual": {"badTime": "mock"}, "expected": { "schema": {"type": "object", "required": ["time"], "properties": {"time": {"type": "string", "format": "date-time"}}} }, "where": "response" }]}
ui(document, pathRoot = "/", skipPaths = []) => koa2 middleware
You can also serve a swagger-ui for your API from a given path root (pathRoot defaults to "/"):
;; const app = ; const document = swagger;app;
app.use(ui(document, "/swagger"))
adds routes /swagger/api-docs and /swagger.
By using the skipPaths
parameter, it is possible to create routes such as:
/api : Swagger UI
/api/api-docs : Swagger API Docs
/api/v1 : Actual API
with:
app;
Debugging
This library uses debug
, which can be activated using the
DEBUG
environment variable:
export DEBUG=swagger2-koa:*
Limitations
- only supports Koa 2-style async/await middleware interface
- requires node version 6 and above
License
MIT