Created
May 16, 2020 10:18
-
-
Save mohanramphp/2e50eaf69741b34c4f918a0e24d6ffc9 to your computer and use it in GitHub Desktop.
controller part for registration
This file contains 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 router = require("express").Router(); | |
const User = require("../model/User"); | |
const bcrypt = require("bcryptjs"); | |
// validation | |
const { registerValidation, loginValidation } = require("../validation"); | |
// register route | |
router.post("/register", async (req, res) => { | |
// validate the user | |
const { error } = registerValidation(req.body); | |
// throw validation errors | |
if (error) return res.status(400).json({ error: error.details[0].message }); | |
const isEmailExist = await User.findOne({ email: req.body.email }); | |
// throw error when email already registered | |
if (isEmailExist) | |
return res.status(400).json({ error: "Email already exists" }); | |
// hash the password | |
const salt = await bcrypt.genSalt(10); | |
const password = await bcrypt.hash(req.body.password, salt); | |
const user = new User({ | |
name: req.body.name, | |
email: req.body.email, | |
password, | |
}); | |
try { | |
const savedUser = await user.save(); | |
res.json({ error: null, data: { userId: savedUser._id } }); | |
} catch (error) { | |
res.status(400).json({ error }); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment