用joi验证整个请求对象

时间:2019-03-20 12:50:21

标签: javascript node.js express joi

我创建了一个中间件,用于在调用控制器逻辑之前验证请求输入。

假设我有一个“通过ID获取用户”-路由

const usersController = require('../controllers/users.js');
const usersControllerPolicy = require('../policies/users.js');

router.get('/:userId', usersControllerPolicy.getUserById, usersController.getUserById);

// other routes

在执行控制器之前,我使用策略来验证参数和主体。我为用户提供的政策模块是

const joi = require('joi');
const schemaValidation = require('../middleware/schemaValidation.js');

module.exports = {
    getUserById: (req, res, next) => {
        schemaValidation({
            userId: joi.string().guid().required()
        }, req, res, next);
    }

    // other routes
}

userId是一个路由参数,而不是主体内的变量。的 schemaValidation中间件验证给定的架构并调用next()或发送400响应。

const joi = require('joi');
const requestResponder = require('../helpers/requestResponder.js');

module.exports = (schema, req, res, next) => {
    const { error } = joi.validate(req, schema);

    if (error)
        return requestResponder.sendBadRequestError(res);

    next();
}

当我用/users/137eaa6f-75c2-46f0-ba7c-c196fbfa367f呼叫此路线时,会出现此错误

  

消息:'“ userId”是必需的'

,但验证应该可以。我通过登录joi.validate(req, schema)检查了验证req.params,并且userId可用。我想念什么?


修改:

我知道我可以验证req.params,但是如果我想更新用户怎么办?我将必须验证参数(userId)和主体(名称,年龄,...)

1 个答案:

答案 0 :(得分:1)

您的joi验证模式应反映req对象的结构,该对象结构应该起作用:

const joi = require('joi');
const schemaValidation = require('../middleware/schemaValidation.js');

module.exports = {
    getUserById: (req, res, next) => {
        schemaValidation(joi.object({
            params: joi.object({
                userId: joi.string().guid().required()
            }).unknown(true)
        }).unknown(true), req, res, next);
    }

    // other routes
}

当您需要同时验证正文和参数时:

const joi = require('joi');
const schemaValidation = require('../middleware/schemaValidation.js');

const paramsValidation = joi.object({
    userId: joi.string().guid().required()
}).unknown(true);

const bodyValidation = joi.object({
    name: joi.string().required()
}).unknown(true);

module.exports = {
    getUserById: (req, res, next) => {
        schemaValidation(joi.object({
            params: paramsValidation,
            body: bodyValidation
        }).unknown(true), req, res, next);
    }

    // other routes
}

但是我宁愿使用3种joi模式(主体,参数,查询)分别对它们进行验证,例如https://www.npmjs.com/package/express-joi-validation#validation-ordering