Express Validator Custom - Nodejs

Asked

Viewed 429 times

1

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

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 said, when the email already exists it triggers an error to the callback function, and as it is not surrounded by try{} catch(){} my application to:

Erro gerado ao enviar um email em uso à minha api

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

1 answer

1


Hello! Express-Validator maintainer here :)

You must use Privileges to make your Asynchronous Validator 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();
            }
        });
    });
})

P.S.: validators .custom() use the message of Error launched. So you don’t need to use .withMessage() after him.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.