EmanuelGF
EmanuelGF

Reputation: 775

Check if email is in database in custom express-validator. (node, express, mysql)

//Update the user's email endpoint.
apiRouter.post('/update-email', [
check('newEmail')
    .isEmail().withMessage('Please Insert a valid Email')
    .custom(newEmail=> {
        db.query(`SELECT user_id FROM users WHERE email = ?`, newEmail,(err, res)=> {
            if(res.length > 0) throw new Error('Email is already registered.');
        });
    })
], (req, res)=> { 
    const errors = validationResult(req);
if (!errors.isEmpty()) {
    return res.status(422).json(errors);
} else {
    const newEmail = req.body.newEmail;
    const id = req.body.id;
    userCRUDfuncs.updateEmail(id, newEmail, db, (err=> {
        if(!err) { 
            return res.status(201).send();
        } else {
            return res.status(404).send();
        }
    }));
}
})

This code returns the following error: "throw err; // Rethrow non-MySQL errors".

I have tried using callbacks and Promises but I can never throw the error outside the query function. I could not find a way to signal the outside function to throw the error. I really appreciate your help on this . Thanks in advance.

Upvotes: 0

Views: 2058

Answers (1)

Rohit Kashyap
Rohit Kashyap

Reputation: 1592

Make your own custom validator and wrap your query inside a promise

  .custom((value, {req}) => {
    return new Promise((resolve, reject) => {
     db.query(`SELECT user_id FROM users WHERE email = ?`, req.body.email,(err,res)=> 
  {
    if(err) {
      reject(new Error('Server Error')
    }

    if(res.length > 0) {
      reject(new Error('E-mail already in use'))
    }

    resolve(true)

    });

  });

})

Upvotes: 3

Related Questions