egg参数校验

2021-01-28  本文已影响0人  梦幽辰

简单介绍

egg-router-auth 基于 apidoc 来构建参数校验

功能

安装

npm i egg-router-auth --save

配置相关

文件目录配置

建议文件目录需按此配置

project
├── app
│   ├── controller
│   │   └── home.js
│   └── router.js
├── apidoc
│   └── output
|       └── api_data.json
│   └── template
|       └── api_data.json
|
|...

开启插件

// config/plugin.js
exports.auth = {
  enable: true,
  package: 'egg-router-auth',
};

配置

// config/config.default.js
config.auth = {
  jwtExclude: ['/api/login', '/api/public/verification'], // 验证用户登录需要跳过的路由
  errorCode: -2, // 错误的code,
  output: 'apidoc/output', // apidoc输出目录,必选
  template: 'apidoc/template' // apidoc模板,可选
}

使用

  // app/controller/home.js
  /**
  * @api {GET} /api/test 普通测试接口
  * @apiParam {string} user 用户名
  */
  async test() {
    const { ctx } = this;
    const res = '测试';
    ctx.body = res;
  }
  
  /**
  * @api {GET} /api/test 多参数类型测试接口
  * @apiParam {string|null} user 用户名
  */
  async test1() {
    const { ctx } = this;
    const res = '测试';
    ctx.body = res;
  }
  
  /**
  * @api {GET} /api/test 可选参数测试接口
  * @apiParam {string} [user] 用户名
  */
  async test2() {
    const { ctx } = this;
    const res = '测试';
    ctx.body = res;
  }
  
  /**
  * @api {GET} /api/test 复杂类型测试接口
  * @apiParam {object} user 用户
  * @apiParam {string} user.name 用户名
  */
  async test3() {
    const { ctx } = this;
    const res = '测试';
    ctx.body = res;
  }

提问交流

请到 egg-router-auth issues 异步交流。

上一篇 下一篇

猜你喜欢

热点阅读