先上 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
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.