Skip to content

Instantly share code, notes, and snippets.

@laere
Created March 17, 2019 12:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laere/6bbd5004dfb0f8040b8bdadfcde67c46 to your computer and use it in GitHub Desktop.
Save laere/6bbd5004dfb0f8040b8bdadfcde67c46 to your computer and use it in GitHub Desktop.
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;
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);
});
{
"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