Commit 372c0ddf authored by Balasuriya D.A.M.'s avatar Balasuriya D.A.M.

Create User Registration API with routes/controllers

parent 5ce68d98
const asyncHandler = require("express-async-handler");
const User = require("../models/userModel");
const registerUser = asyncHandler(async (req, res) => {
const { name, email, password, pic } = req.body;
if (!name || !email || !password) {
res.status(400);
throw new Error("Please Enter all the Feilds");
}
//If user is already exists
const userExists = await User.findOne({ email }); // query get from MongoDB
if (userExists) {
res.status(400);
throw new Error("User already exists");
}
//otherwise create new user
//user.create get from MongoDB
const user = await User.create({
name,
email,
password,
pic,
});
if (user) {
res.status(201).json({
_id: user._id,
name: user.name,
email: user.email,
pic: user.pic,
});
} else {
res.status(400);
throw new Error("Failed to Create the User");
}
});
module.exports = { registerUser };
\ No newline at end of file
...@@ -2,11 +2,11 @@ const mongoose = require("mongoose"); ...@@ -2,11 +2,11 @@ const mongoose = require("mongoose");
const userSchema = mongoose.Schema({ const userSchema = mongoose.Schema({
name: { type: String, required: true }, name: { type: String, required: true },
email: { type: String, required: true }, email: { type: String, required: true,unique:true },
password: { type: String, required: true }, password: { type: String, required: true },
pic: { pic: {
type: String, type: String,
required: true, //required: true, if it is required i can use this reuired as true
default: default:
"https://icon-library.com/images/anonymous-avatar-icon/anonymous-avatar-icon-25.jpg", "https://icon-library.com/images/anonymous-avatar-icon/anonymous-avatar-icon-25.jpg",
}, },
......
const express = require("express"); const express = require("express");
const { registerUser } = require("../controllers/userControllers");
const router = express.Router(); const router = express.Router();
//router.route("/").post(registerUser) router.route("/").post(registerUser);
//router.post("/login",authUser) //router.post("/login",authUser)
module.exports = router; module.exports = router;
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment