问题
I have a problem to return boolean (true or false) if user already exist or not in custom express-validator. So far I manage to work it in this way:
app.use(expressValidator({
customValidators: {
isUsernameAvailable: function (username) {
return User
.findOne({ 'username': username })
.then(function (user) {
if (user) {
throw new Error('User already exist')
}
}
}
}
The idea is to return boolean (corresponding the name: isUsernameAvailable) not Promise or Object, but I don't know how.
I used it to check it in this way:
module.exports = {
create: (req, res) => {
let user = req.body
...
req.check('username', 'This username is already taken.').isUsernameAvailable()
...
}
}
回答1:
i taken more time to get easy and simplify code for do it
this is my code i used it
router.post('/signup', [
check('username').notEmpty().withMessage('must be not null').
.custom((value, {req, loc, path}) => {
return Users.findOne({
where: {
username: req.body.username,
}
}).then(user => {
if (user) {
return Promise.reject('Username already in use');
}
});
})
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({errors: errors.array()});
} else {
// Do everything or create new user
}
});
回答2:
you haven't described how your "check" function will know if the username is a duplicate or not, but I will say that I can't think of a scalable solution that doesn't require a trip to some form of data store (database being the most common). In Node, that means an asynchronous call involving a callback or Promise unless you really want to work hard to make it synchronous.
And honestly, any multiuser app with uniqueness requirements is going to get into trouble eventually with a check like you describe because your check and create steps will not be inside a single atomic transaction.
Far better and more scalable to simply apply a unique index to the field in the database, then handle that error appropriately in your app code.
来源:https://stackoverflow.com/questions/40376557/how-to-check-is-user-already-exist-with-customvalidators-in-express-validator