@atlaslabs/koa-swagger-decorator

中文文档
0.2.118发布于 2021/12/02MITCommonJS近 30 天下载 9305

using decorator to automatically generate swagger doc for koa-router

原始使用文档
文档目录8 节
  1. Installation
  2. Contributing Guide
  3. Introduction
  4. Koa Swagger Decorator
  5. Example
  6. Requirements
  7. Detail
  8. License

koa-swagger-decorator

using decorator to auto generate swagger json docs

build status npm

Installation

npm install koa-swagger-decorator

Contributing Guide

Please refer to contribution.md before creating your PR or issue.

Introduction

Koa Swagger Decorator

using decorator to auto generate swagger json docs add support validation for swagger definitions

based on Swagger OpenAPI Specification 2.0

support both javascript (babel required) and typescript

Example

// using commonds below to start and test the example server

git clone https://github.com/Cody2333/koa-swagger-decorator.git

cd koa-swagger-decorator

npm install

npm run start

finally open:
http://localhost:3000/api/swagger-html

Requirements

  • Koa2
  • koa-router
  • babel support for decorator (or using typescript)
// add [transform-decorators-legacy] to .babelrc if using js

npm install --save-dev babel-plugin-transform-decorators-legacy

{
  "presets": [
    ["env", {"targets": {"node": "current"}}]
  ],
  "plugins": ["transform-decorators-legacy"]
}

Detail

for more detail please take a look at the example koa server

first wrapper the koa-router object

// router.js
import Router from 'koa-router'

import Test from './test'

import { SwaggerRouter } from 'koa-swagger-decorator'

const router = new SwaggerRouter([KoaRouterOpts],[SwaggerOpts]) // extends from koa-router

// swagger docs avaliable at http://localhost:3000/api/swagger-html
router.swagger({
  title: 'Example Server',
  description: 'API DOC',
  version: '1.0.0',

  // [optional] default is root path.
  // if you are using koa-swagger-decorator within nested router, using this param to let swagger know your current router point
  prefix: '/api',

  // [optional] default is /swagger-html
  swaggerHtmlEndpoint: '/swagger-html',

  // [optional] default is /swagger-json
  swaggerJsonEndpoint: '/swagger-json',

  // [optional] additional options for building swagger doc
  // eg. add api_key as shown below
  swaggerOptions: {
    securityDefinitions: {
      api_key: {
        type: 'apiKey',
        in: 'header',
        name: 'api_key',
      },
    },
  },
  // [optional] additional configuration for config how to show swagger view
  swaggerConfiguration: {
    display: {
      defaultModelsExpandDepth: 4, // The default expansion depth for models (set to -1 completely hide the models).
      defaultModelExpandDepth: 3, // The default expansion depth for the model on the model-example section.
      docExpansion: 'list', // Controls the default expansion setting for the operations and tags. 
      defaultModelRendering: 'model' // Controls how the model is shown when the API is first rendered. 
    }
  }
})
// map all static methods at Test class for router
// router.map(Test);

// mapDir will scan the input dir, and automatically call router.map to all Router Class
router.mapDir(_path.resolve(__dirname), {
  // default: true. To recursively scan the dir to make router. If false, will not scan subroutes dir
  // recursive: true,
  // default: true, if true, you can call ctx.validatedBody[Query|Params] to get validated data.
  // doValidation: true,
  // default: [], paths to ignore while looking for decorators 
  // ignore: ["**.spec.ts"],
})

using decorator to make api definition

// test.js

import User from 'models/user'
import { request, summary, query, path, body, tags } from 'koa-swagger-decorator'

const testTag = tags(['test'])

const userSchema = {
  name: { type: 'string', required: true },
  gender: { type: 'string', required: false, example: 'male' },
  groups: {
    type: 'array',
    required: true,
    items: { type: 'string', example: 'group1' }, // item's type will also be validated
  },
}

export default class Test {
  @request('get', '/users')
  @summary('get user list')
  @security([{ api_key: [] }])
  @testTag
  @query({
    type: { type: 'number', required: true, default: 1, description: 'type' },
  })
  static async getUsers(ctx) {
    const users = await User.findAll()
    ctx.body = { users }
  }

  @request('get', '/users/{id}')
  @summary('get user info by id')
  @security([{ api_key: [] }])
  @testTag
  @path({
    id: { type: 'number', required: true, default: 1, description: 'id' },
  })
  static async getUser(ctx) {
    const { id } = ctx.validatedParams
    const user = await User.findById(id)
    ctx.body = { user }
  }

  @request('post', '/users')
  @testTag
  @body(userSchema)
  static async postUser(ctx) {
    // const body = ctx.request.body;
    const body = ctx.validatedBody
    ctx.body = { result: body }
  }

  static async temp(ctx) {
    ctx.body = { result: 'success' }
  }
}

using decorator to make api body

import Router from 'koa-router';
import { request, summary, query, path, body, tags, swaggerClass, swaggerProperty } from 'koa-swagger-decorator'

@swaggerClass()
export class subObject {
  @swaggerProperty({ type: "string", required: true }) Email: string = "";
  @swaggerProperty({ type: "string", required: true }) NickName: string = "";
  @swaggerProperty({ type: "string", required: true }) Password: string = "";
};

@swaggerClass()
export class userInfo {
  @swaggerProperty({ type: "string", required: true }) Email: string = "";
  @swaggerProperty({ type: "string", required: true }) NickName: string = "";
  @swaggerProperty({ type: "string", required: true }) Password: string = "";
  @swaggerProperty({type:"object",properties:(subObject as any).swaggerDocument}) UserInfo:subObject;
};

export default class Test {
  @request('POST', '/user/Register')
  @summary('register user')
  @description('example of api')
  @body((userInfo as any).swaggerDocument)
  static async Register(ctx: Router.IRouterContext) {
    var params = (ctx as any).validatedBody as userInfo;
    console.log(params);
  }
}

avaliable annotations

  • tags
  • query
  • path
  • body
  • formData
  • middlewares
  • security
  • summary
  • description
  • responses
  • deprecated

class annotations

  • tagsAll
  • responsesAll
  • middlewaresAll
  • securityAll
  • deprecatedAll
  • queryAll
request // @request('POST', '/users')

tags // @tags(['example'])
query // @query({limit: {type: 'number', required: true, default: 10, description: 'desc'}})

path // @path({limit: {type: 'number', required: true, default: 10, description: 'desc'}})

body // @body({groups: {type: 'array', required: true, items: { type: 'string', example: 'group1' }}})

formData // @formData({file: {type: 'file', required: true, description: 'file content'}})

middlewares
// support koa middlewares.
// eg. @middlewares([func1,func2])

security 
// define authentication method, key must be same as one of methods defined in swaggerOptions.securityDefinitions
// @security([{ api_key: [] }]) 

summary // @summary('api summary')

description // @description('api description')

responses
// @responses({ 200: { description: 'success'}, 400: { description: 'error'}})
// responses is optional

deprecated // @deprecated

@tagsAll(['A', 'B'])
@deprecatedAll
@securityAll([{ api_key: [] }])
@middlewaresAll([log1, log2]) // add middlewares [log1, log2] to all routers in this class
@queryAll({ limit: { type: 'number', default: 444, required: true } }) // can be merged with @query
export default class SampleRouter {
  ...
}

validation

support validation type: string, number, boolean, object, array.

properties in {type: 'object'} and items in {type: 'array'} can alse be validated.

other types eg. integer will not be validated, and will return the raw value.

by default, validation is activated and you can call ctx.validatedQuery[Body|Params] to access the validated value.

to turn off validation:

router.mapDir(_path.resolve(__dirname), {
  // default: true, if true, you can call ctx.validatedBody[Query|Params] to get validated data.
  doValidation: false,
})
runing the project and it will generate docs through swagger ui

image.png

License

© MIT

版本与发布记录

@atlaslabs/koa-swagger-decorator 共发布 10 个版本,首次发布于 2020/03/13;过去 12 个月发布了 0 个版本。

版本发布日期距今
0.2.118latest2021/12/024 年前
0.2.1172021/11/124 年前
0.2.1162021/10/225 年前
0.2.12021/01/185 年前
0.1.612020/11/056 年前
0.1.42020/08/116 年前

关于 @atlaslabs/koa-swagger-decorator 的常见问题

@atlaslabs/koa-swagger-decorator 是什么?

using decorator to automatically generate swagger doc for koa-router

如何安装 @atlaslabs/koa-swagger-decorator?

在项目目录运行 npm install @atlaslabs/koa-swagger-decorator,或使用 pnpm add / yarn add / bun add。

@atlaslabs/koa-swagger-decorator 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/atlaslabs__koa-swagger-decorator 是否存在。

@atlaslabs/koa-swagger-decorator 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@atlaslabs/koa-swagger-decorator 可以商用吗?

@atlaslabs/koa-swagger-decorator 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@atlaslabs/koa-swagger-decorator 的下载量有多少?

根据 npm 官方下载统计,@atlaslabs/koa-swagger-decorator 在 2026/10/07 – 2026/11/05 这 30 天内被下载 9,305 次,日均约 310 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@atlaslabs/koa-swagger-decorator 还在维护吗?

最新版本 0.2.118 发布于 2021/12/02(4 年前);至今共发布 10 个版本,其中过去 12 个月发布了 0 个;首次发布于 2020/03/13。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。