Search code examples
node.jsexpressmiddleware

Express.js error with route validated path param via middleware


I got this middleware for the following route:

router.param('userId', (req, res, next, val) => {
            if (!/^\d+$/i.test(val)) {
                globalResponse.sendResponse(res, 400, `la sintaxis de entrada no es válida para integer: «${val}»`, true);
            } else {
                next();
            }
        });

the route is :

router.get('/user/:userId', (req, res) => {
        let userId = req.params.userId,
            criteria = {};
        criteria.userId = Number(userId);
        users.findUserByCriteria(criteria)
            .then(userFinded => {
                if (userFinded != null) {
                    globalResponse.sendResponse(res, 200, userFinded, false);
                } else {
                    globalResponse.sendResponse(res, 404, `Usuario ${userId} no Encontrado.`, true);
                }
            })
            .catch(err => {
                globalResponse.sendResponse(res, 500, err, true)
            });
    });

all ok, the error is when try use other route '/user/' the middleware Valid without this the path param 'userId'

router.get('/user/all', (req, res) => {
        users.findAllUsers()
            .then(allUsers => {
                globalResponse.sendResponse(res, 200, allUsers, false);
            })
            .catch(err => {
                globalResponse.sendResponse(res, 500, err, true);
            });
    });

then in 'user/all' valid and this not is necesary


Solution

  • You can make some changes to accept all parameter

     router.param('userId', (req, res, next, val) => {
        if(val=="all")  
       {
        next();
       }else if (!/^\d+$/i.test(val)) {
                        globalResponse.sendResponse(res, 400, "la sintaxis ...", true);
                    } else {
                        next();
                    }
                });
    

    and in your later code

     let userId = req.params.userId,
    if(userId=="all"){
     users.findAllUsers()
                .then(allUsers => {
                    globalResponse.sendResponse(res, 200, allUsers, false);
                })
                .catch(err => {
                    globalResponse.sendResponse(res, 500, err, true);
                });
    } 
    
    .........
    ......
    

    You dont need this router router.get('/user/all', (req, res) => {