Express Validator Custom - NodeJS

1
I'm using express-validator in my api to validate the received data, I'm creating a custom validation to check if the user's email is already registered in the system, but I can not fire a throw new Error('Email em uso'); validator since my sql query is returned in a callback function, so if I use throw new Error it is directed to the callback function and not the main one.

My code:

app.post('/account/new/validate', [
    body('emailRegistro')
        .isLength({ min: 5, max: 50 })
        .isEmail()
        .custom((emailRegistro) => {
            accountModel.VerificarEmailExistente(sql, emailRegistro, (error, result) => {
                console.log("Chegou aqui - 1");
                if(result.length !== 0){
                    console.log("Chegou aqui - 2");
                    throw new Error('Email em uso'); //Erro disparado a função de callback do sql.query, esse erro precisa ir para a função principal
                    return;
                }
            });
        })
        .withMessage('Email Inválido')
], (req, res, next) => {
    try{
        validationResult(req).throw();
        //Validações concluídas
        console.log("OK");
    }catch(err){
        //Retorno dos erros de validação
        return res.json({ errors: err.mapped() });
    }
});

As I already said, when the email already exists it triggers an error to the callback function, and since it is not surrounded by try{} catch(){} my application to:

How can I get out of this situation and trigger an error for the main function?

    
asked by anonymous 08.09.2017 / 22:40

1 answer

1

Hello! Express-validator maintainer here:)

You should use promises to make your asynchronous validator in the express-validator. It would look something like this:

.custom((emailRegistro) => {
    return new Promise((resolve, reject) => {
        accountModel.VerificarEmailExistente(sql, emailRegistro, (error, result) => {
            if(result.length !== 0){
                reject(new Error('Email em uso'));
            } else {
              resolve();
            }
        });
    });
})

Q.: .custom() validators use the Error message posted. So you do not have to use .withMessage() after it.

    
02.10.2017 / 15:33