先上 github 地址 koa-proper
最近写 node 服务端写多了,每个接口都要进行参数验证。 重复代码很多,所以抽象了一个中间件。
功能:
使用简单,功能实用,话不多说看代码:
import Koa from 'koa' import proper from 'koa-proper' const app = new Koa() app.use(proper()) app.use(async ctx => { // 请求参数: {string: any} const props = ctx.request.query // 定义参数类型: {string: PropType} // ctx.PropTypes 就是 prop-types const types = { username: ctx.PropTypes.string.isRequired } // ctx.proper 为验证方法 // 如果验证通过,返回原数据 const params = ctx.proper(props, types) // 如果失败, 会自动抛出 http error // 可以在 options 里关闭或者自定义 // ctx.throw(400, error) <---- 默认的错误抛出方法 // 验证通过才会执行下面代码 ctx.body = params })
再上 github 地址 koa-proper