Thursday, 26 September 2019

express-validator returns validation errors twice

I want to validate the request object using Express-Validator. Let's assume I have two routes, a GET /users/:id (fetchUserById) and POST /users (createUser) route

this.router = express.Router();
this.router.route('/').post(this.userRequestValidator.createUser, this.userController.createUser);
this.router.route('/:id').get(this.userRequestValidator.fetchUserById, this.userController.fetchUserById);

As you can see I call the validation middleware right before calling the controller logic. First I created a base validator dealing with the validation errors and returning a HTTP 400 if something failed.

export abstract class RequestValidator {
    protected validate = async (request: Request, response: Response, next: NextFunction): Promise<void> => {
        const errors: Result<ValidationError> = validationResult(request);

        if (!errors.isEmpty()) {
            return res.status(422).json({ errors: errors.array() });
        } else {
            next();
        }
    };
}

My validator functions userRequestValidator.createUser and userRequestValidator.fetchUserById just have to extend the RequestValidator and implement the validations

export class UserRequestValidator extends RequestValidator {
    public createUser = [
        body('username')
            .isString()
            .exists(),
        body('password')
            .isString()
            .exists(),
        this.validate,
    ];

    public fetchUserById = [
        param('id')
            .isString()
            .isUUID()
            .exists(),
        this.validate,
    ];
}

When I call GET localhost:3000/users/abc I get this response

{
    "errors": [
        {
            "value": "abc",
            "msg": "Invalid value",
            "param": "id",
            "location": "params"
        }
    ]
}

This is the response I am expecting. But when I call POST localhost:3000/users with an empty body I get this response

{
    "errors": [
        {
            "msg": "Invalid value",
            "param": "username",
            "location": "body"
        },
        {
            "msg": "Invalid value",
            "param": "username",
            "location": "body"
        },
        {
            "msg": "Invalid value",
            "param": "password",
            "location": "body"
        },
        {
            "msg": "Invalid value",
            "param": "password",
            "location": "body"
        }
    ]
}

Does someone know how I can fix this behaviour or what's wrong with my setup?



from express-validator returns validation errors twice

No comments:

Post a Comment