Created
July 5, 2020 06:51
-
-
Save suhas86/fc3fb36b14a496339363de9b5735da6b to your computer and use it in GitHub Desktop.
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
import express, { Request, Response } from "express"; | |
import { User } from "../models/user"; | |
import { body, check, validationResult } from "express-validator"; | |
const router = express.Router(); | |
router.post( | |
"/api/users/signup", | |
[ | |
body("firstName") | |
.trim() | |
.not() | |
.isEmpty() | |
.withMessage("First Name is required"), | |
body("email").isEmail().withMessage("Email must be valid"), | |
body("password") | |
.trim() | |
.isLength({ min: 6 }) | |
.withMessage("Password must be minimum of 6 characters"), | |
check("password").custom((val, { req }) => { | |
if (val !== req.body.confirmPassword) { | |
throw new Error("Passwords don't match"); | |
} else { | |
return val; | |
} | |
}), | |
], | |
async (req: Request, res: Response) => { | |
const errors = validationResult(req); | |
if (!errors.isEmpty()) { | |
return res.status(400).send(errors.array()); | |
} | |
const { firstName, lastName, email, password } = req.body; | |
const existingUser = await User.findOne({ email }); | |
if (existingUser) { | |
return res.status(400).send({ error: "Email already exists" }); | |
} | |
const user = new User({ email, firstName, lastName, password }); | |
await user.save(); | |
return res.status(201).send(user); | |
} | |
); | |
export { router as SignupRoute }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment