Created
March 17, 2019 12:18
-
-
Save laere/6bbd5004dfb0f8040b8bdadfcde67c46 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Joi = require("joi"); | |
const registerValidationSchema = Joi.object().keys({ | |
name: Joi.string() | |
.min(2) | |
.max(30) | |
.required(), | |
email: Joi.string() | |
.email() | |
.required(), | |
password: Joi.string() | |
.min(6) | |
.required() | |
}); | |
module.exports = registerValidationSchema; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
router.post("/register", (req, res, next) => { | |
const userProps = req.body; | |
const { email } = userProps; | |
User.findOne({ email }) | |
.then(user => { | |
if (user) { | |
return res.status(400).json({ errormessage: "User already exists." }); | |
} else { | |
const avatar = gravatar.url(email, { | |
s: "200", // Size | |
r: "pg", // Rating | |
d: "mm" // Default | |
}); | |
const newUser = new User({ ...userProps, avatar }); | |
Joi.validate(newUser, userValidationSchema, { | |
abortEarly: false | |
}); | |
bcrypt.genSalt(10, (err, salt) => { | |
bcrypt.hash(newUser.password, salt, (err, hash) => { | |
if (err) { | |
next(err); | |
} | |
newUser.password = hash; | |
newUser | |
.save() | |
.then(user => res.json(user)) | |
.catch(err => res.status(400).json(err)); | |
}); | |
}); | |
} | |
}) | |
.catch(next); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"errors": { | |
"name": { | |
"message": "Path `name` is required.", | |
"name": "ValidatorError", | |
"properties": { | |
"message": "Path `name` is required.", | |
"type": "required", | |
"path": "name", | |
"value": "" | |
}, | |
"kind": "required", | |
"path": "name", | |
"value": "" | |
}, | |
"email": { | |
"message": "Path `email` is required.", | |
"name": "ValidatorError", | |
"properties": { | |
"message": "Path `email` is required.", | |
"type": "required", | |
"path": "email", | |
"value": "" | |
}, | |
"kind": "required", | |
"path": "email", | |
"value": "" | |
} | |
}, | |
"_message": "users validation failed", | |
"message": "users validation failed: name: Path `name` is required., email: Path `email` is required.", | |
"name": "ValidationError" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment