2.0.1 • Published 2 years ago

koa-router-simple v2.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

koa-router-simple

基于koa2的路由封装中间件,只需按照统一格式配置路由对象即可,并集成了参数类型校验功能。

安装

使用NPM

  npm i -S koa-router-simple

使用YARN

  yarn add koa-router-simple

使用方式:

CommonJS模块引入

  const simpleRouter = require('koa-router-simple');
  // 使用 koa-router-simple
  const app = new Koa();
  app.use(simpleRouter(allRoutes));

其中allRoutes表示项目中所有的路由对象数组,其格式如下:

  allRoutes = [...UserRouter, ...OtherRouter]

其中UserRouter、OtherRouter表示需要用户配置的路由对象,格式如下:

  UserRouter = [
    {
      url: '/user/login',
      method: 'post',
      // params: null,
      params: {
        username: {
          type: ['string', 'number'],
          required: true
        },
        password: {
          type: 'string',
          required: true
        }
      },
      handler: async(ctx, next) {
        // url路由对应的具体处理逻辑
      }
    }
  ]

请求参数校验:

  • params属性表示需要对请求参数进行校验的规则,其中表示要校验的参数名,该键所对应的对象为具体的规则。
  • 其中type表示参数值的类型,值为字符串或者字符串数组,字符串内容为使用运算符typeof能够得到的值。
  • required表示该参数是否必须传递。

当校验完之后,会出现如下两种情况:

  • 一种是参数规则匹配正确,此时无任何副作用(影响)。
  • 第二种情况就是参数规则匹配不对应,此时,将产生副作用:
    • ctx.response.status 被设置为400
    • ctx.request.paramsErrors 被设置为具体的校验异常信息数组(errors)

errors的格式如下:

  errors = [
    {
      code: number,  //0 | 1,0表示参数值类型异常,1表示参数缺失异常。
      key: string,   // "校验失败的字段名"
      value: any,    // "校验失败的字段值"
      type: string   // "该字段值的正确类型"
    }
  ]

开发者可以通过检测ctx.response.status来判断参数校验是否有异常;或者可以通过ctx.request.paramsErrors的长度来判断是否有参数校验异常,且可以根据该字段中的具体的校验异常对象信息来组装返回信息给接口调用方。

注意

此中间件基于包@koa/routerkoa-body,如需使用此中间件,需要先安装以上两个包!

2.0.1

2 years ago

2.0.0

2 years ago

1.2.0

2 years ago

1.1.0

2 years ago

1.0.0

2 years ago