diff --git a/models/user.js b/models/user.js index d841480d8..9446a949b 100644 --- a/models/user.js +++ b/models/user.js @@ -426,3 +426,20 @@ UserService.search = (value) => { ] }); }; + +/** + * Finds users by email and returns the count. The result should be 1 or 0 (bool) indicating email availability + * @param {String} email to search by + * @return {Promise} + */ +UserService.availabilityCheck = (email) => { + return UserModel.count({ + profiles: { + $elemMatch: { + id: email, + provider: 'local' + } + } + }); +}; + diff --git a/routes/api/user/index.js b/routes/api/user/index.js index ce594168c..a702adb41 100644 --- a/routes/api/user/index.js +++ b/routes/api/user/index.js @@ -69,25 +69,17 @@ router.post('/availability', (req, res, next) => { const {email} = req.body; if (email) { - return User.count({ - profiles: { - $elemMatch: { - id: email, - provider: 'local' + return User.availabilityCheck(email) + .then(count => { + if (count) { + return res.json({status: 'unavailable'}); } - } - }) - .then(count => { - if (count) { - return res.json({status: 'unavailable'}); - } - return res.json({status: 'available'}); - }) - .catch(err => { - next(err); - }); + return res.json({status: 'available'}); + }) + .catch(err => { + next(err); + }); } - return res.status(404).send('Wrong parameters'); });