美文网首页
egg参数校验

egg参数校验

作者: 梦幽辰 | 来源:发表于2021-01-28 10:24 被阅读0次

简单介绍

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

功能

  • 在egg项目中验证路由表中是否包含请求的url,如果请求了路由表中未存在的路由,则会提示相应信息

  • 在egg项目中验证在许可的路由中是否存在用户的jwt登录

  • 验证路由的参数

安装

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 异步交流。

相关文章

网友评论

      本文标题:egg参数校验

      本文链接:https://www.haomeiwen.com/subject/rkiwkktx.html