npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@yassine-zhang/express-joi

v1.0.1

Published

提供对于joi包的Express验证中间件

Downloads

1

Readme

前言

在基于Node.js Express框架的后端API开发中我想使用一个可以粗略快速验证前端发来的表单数据的工具包,就此发现了joi的存在,joi真的很不错,但它的正则表达式做的貌似并不怎么好。

因为要保持Express高度统一的规范,所以我想通过中间件的方式来验证数据,但是并没有发现基于目前[email protected]版本的包,故此我开发了@yassine-zhang/express-joi这么一个包。

如何使用?

安装

npm install @yassine-zhang/express-joi

导入joi包,创建基础验证条件

在下面代码中我简单创建了验证条件,注意:这些都是[email protected]最新用法

joi.object() -创建验证条件

object.with() -必须且只允许验证时传来哪些数据键

const joi = require('joi')

const username = joi.string().alphanum().min(3).max(8).required()
const password = joi.string().pattern(/^[\S]{6,12}$/)

reg_user_schema = joi.object({
    username,
    password
}).with('username', 'password')

注册中间件

当我们验证req.body内数据条件通过后即可继续运行后面路由(默认验证请求体内数据)

如果我们需要获取到请求体内数据的话请自行添加内置全局中间件:express.json()或express.urlencoded({extended: false}),又或者有其他需求。

const express = require('express')
const expressJoi = require(‘@zhangsir/express-joi’)

const app = express()

app.post('/reguser', expressJoi.validate(reg_user_schema), (req, res) => {
    ...
})

添加校验失败错误级别中间件

// 注册辅助反馈响应数据的方法
app.use((req, res, next) => {
    // status = 0 为成功,status = 1 为失败; 默认status = 1,方便处理失败的情况
    res.cc = (err, status=1) => {
        res.send({
          	// 状态
          	status,
            // 状态描述, 判断err是错误对象还是字符串
          	message: err instanceof Error ? err.message : err
        })
    }

    next()
})


// 注册全局错误级别中间件
app.use((err, req, res, next) => {
    // 错误实例类型为 ValidationError , 表单数据校验失败
    if (err instanceof joi.ValidationError) return res.cc(err)

    // 未知报错
    res.cc(err)
})

换源

验证时要从哪里拿数据?body?query? or params?

我们默认在验证时要拿 req.body 的数据,当然在调用验证中间件函数的时候可以传入第二个参数来更换数据源,只在你当前位置验证时有效

案例

如下案例可以在验证时使用 req.params,也就是Express框架URL上的动态参数

app.post('/reguser', expressJoi.validate(reg_user_schema, 'params'), (req, res) => {
    ...
})

当然我们可以传入body | query | params body就是默认的,不需要填,如果填写query,就是获取的URL中查询字符串

联系