V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
4074
V2EX  ›  Node.js

[分享]koa 请求参数验证 middlware

  •  
  •   4074 · 2019-06-03 16:37:05 +08:00 · 4470 次点击
    这是一个创建于 1760 天前的主题,其中的信息可能已经有所发展或是发生改变。

    先上 github 地址 koa-proper

    最近写 node 服务端写多了,每个接口都要进行参数验证。 重复代码很多,所以抽象了一个中间件。

    功能:

    • 对参数对象进行类型验证,基于 prop-types (一个 react 衍生的类型定义库)
    • 验证失败自动抛出 http 400 错误 (可关闭,可自定义)

    使用简单,功能实用,话不多说看代码:

    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

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4053 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 10:18 · PVG 18:18 · LAX 03:18 · JFK 06:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.