swagger2-koa

Koa 2 middleware for loading, parsing and validating requests via swagger2

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 validatemiddleware, and returns a Router object that allows you to add your route implementations.

import * as swagger from 'swagger2';
import {ui, router as swaggerRouter, Router} from 'swagger2-koa';

...
const document = swagger.loadDocumentSync('./swagger.yml');
const router: Router = swaggerRouter(document);

router.get('/ping', async (context) => {
  context.status = 200;
  context.body = {
    serverTime: new Date().toISOString()
  };
});

...

router.app()         // get the koa 2 server
  .use(ui(document)) // only needed if you want to publish a swagger-ui for the API
  .listen(3000);     // start handling requests on port 3000

Note: in addition to validate(described below), routeradds 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:

import * as swagger from 'swagger2';
import { validate } from 'swagger2-koa';

const app = new Koa();

// 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`);
}

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

The validatemiddleware 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 "/"):

import * as swagger from 'swagger2';
import { ui } from 'swagger2-koa';

const app = new Koa();

const document = swagger.loadDocumentSync('./swagger.yml');
app.use(ui(document));

app.use(ui(document, "/swagger"))adds routes /swagger/api-docs and /swagger.

By using the skipPathsparameter, it is possible to create routes such as:

/api          : Swagger UI
/api/api-docs : Swagger API Docs
/api/v1       : Actual API

with:

app.use(ui(document, "/api", ['/api/v1']));

Debugging

This library uses debug, which can be activated using the DEBUGenvironment variable:

export DEBUG=swagger2-koa:*

Limitations

  • only supports Koa 2-style async/await middleware interface
  • requires node version 10 and above

License

MIT

HomePage

https://github.com/carlansley/swagger2-koa#readme

Repository

https+https://github.com/carlansley/swagger2-koa


上一篇:解构reselect
下一篇:swagger-watcher

相关推荐

  • 阿里云centOS部署vue全家桶+node+koa2+mongo项目

    写在前面 文章有丢丢长,前端开发第一次部署项目,有问题请及时提出,以免误导其他童鞋,轻拍~, 更新系统 安装mongo 1. 添加MongoDB源 在/etc/yum.repos....

    1 年前
  • 通过编写一个路由中间件来学习 Koa

    混了四年的大学生活结束了,校招没有找到工作的我还面临着失业。没办法,只有临时抱抱佛脚看看能不能找个工作了。据说最近前端圈里不会 NodeJs 是不可能找到工作的,于是抱起了 NodeJs 里比较流行的...

    2 年前
  • 通过koa2和Promise.race()构造一个超时取消的ajax。

    MDN上说: 你可以使用AbortController.AbortController()构造函数创建一个新的AbortController对象。 使用AbortSignal 对象完成与DOM请求...

    1 年前
  • 适合初学者的koa2+mongodb初体验

    图片描述(https://img.javascriptcn.com/d9403c36f90d60138d8d3fd492c66355 "图片描述") 前言      笔者的前端开发已经有些时日了...

    1 年前
  • 踩坑记之基于Vue+Element+Koa实现云上存储

    前言最近在做项目等时候,需要处理图片,表格,文本等多种格式的文件到数据库,用传统等方法进行处理既繁琐又比较麻烦,所以第一次尝试使用云上存储等方式来实现。比较了阿里云和腾讯云之类的网站之后,最终选择七牛...

    1 个月前
  • 跨域cors 和 jsnop | koa 提供服务器 (实例前端 -后端演示)

    文章目的 验证一下对跨域的理解 前端需要都需要配置 后端相应配置什么 首先跨域方式不止这两种 iframe.posetMessage form 表单也可。 ==== 项目地址 (https:/...

    7 个月前
  • 超轻量级web框架koa源码阅读

    koa是一个非常轻量的web框架,里面除了ctx和middleware之外什么都没有,甚至连最基本的router功能都需要通过安装其他中间件来实现。不过虽然简单,但是它却非常强大,仅仅依靠中间件机制就...

    2 年前
  • 详解React项目的服务端渲染改造(koa2+web

    因为对网页SEO的需要,要把之前的React项目改造为服务端渲染,经过一番调查和研究,查阅了大量互联网资料。成功踩坑。 选型思路:实现服务端渲染,想用React最新的版本,并且不对现有的写法做大的改...

    2 年前
  • 记一次 React + Koa + Mysql 构建个人博客

    前言 由于一直在用 vue 写业务,为了熟悉下 react 开发模式,所以选择了 react。数据库一开始用的是 mongodb,后来换成 mysql 了,一套下来感觉 mysql 也挺好上手的。

    1 年前
  • 让我们来重新设计一下 koa-router

    前言 koarouter 是目前用的比较多的 Koa 的路由中间件之一,前段时间由于作者没有精力继续维护而将其公开售卖(https://www.zhihu.com/question/3106049...

    1 年前

官方社区

扫码加入 JavaScript 社区