Node.js将2种中间件变成1

时间:2019-08-08 17:19:43

标签: javascript node.js

大家好,所以我在expressJS中有一个中间件发布方法,我想在这里简化一下:原始发布方法:

router.post('/', Validate.Schemas('CreateUser'), Validate.validate, (req, res) => {

});

,我想将其更改为此:

router.post('/', Validate.Schemas('CreateUser').validate, (req, res) => {

});

这是Validate文件:

const { body, validationResult } = require('express-validator/check');

exports.validate = (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(422).json({ errors: errors.array() })
    }
};

exports.Schemas = (schema) => {
    switch (schema) {

        //Create New User Schema
        case 'CreateUser': {
            return [
                body('username', 'Invalid input.').exists().isString(),
                body('password', 'Invalid input.').exists().isString(),
                body('email', 'Invalid input.').exists().isEmail(),
                body('DOB', 'Invalid input.').exists(),
                body('products').optional().isArray(),
                body('isStaff').optional().isBoolean(),
            ]
        }


    }
};

感谢您的帮助。

0 个答案:

没有答案
相关问题