discuss
discuss copied to clipboard
Whats wrong with this example ?
Hi guys I'm just trying to make a pre validation on the Hapi route, this is my code:
function verifyUniqueUser(req, h){
// Find an entry from the database that
// matches either the email or username
let response = req.payload;
User.findOne({ email: req.payload.email }, (err, user) => {
// Check whether the username or email
// is already taken and error out if so
if (user) {
if (user.email === req.payload.email) {
response = Boom.badRequest('The email is already registered');
}
}
if(err) {
console.log(err);
}
// If everything checks out, send the payload through
// to the route handler
});
return response;
}
And I'm using it with:
method: 'POST',
path: '/api/register',
handler: register,
options: {
pre: [
{ method: verifyUniqueUser, assign: 'uniqueValidator' }
],
validate: {
payload: UserJoiValidator,
failAction: handleError
}
}
But nothing happens, in request.pre.uniqueValidator I just see the current payload.
I need to add or modify something ?.
Thanks.
Since the (err, user) => ... callback is called asynchronously but your function returns synchronously, the response does not have a chance to be modified before the function returns. If User.findOne() supports promises, then something like this should work:
async function verifyUniqueUser(req, h) {
// Find an entry from the database that
// matches either the email or username
const user = await User.findOne({ email: req.payload.email });
if (user && user.email === req.payload.email) {
throw Boom.badRequest('The email is already registered');
}
return req.payload;
}
And if it does not support promises then you will need to promisify it.