done refactoring User controller + UserModel

This commit is contained in:
Kfir Dayan 2023-06-21 14:44:05 +03:00
parent d1ed7dfbcc
commit 8f60cc1e54
7 changed files with 201 additions and 115 deletions

View file

@ -1,90 +1,101 @@
import { Request, Response } from 'express'; import { Request, Response } from 'express';
// import { createUser } from '../models/userModel'; import { createUser, loginUser, getAllUsers, deleteUser } from '../models/userModel';
import { IUser } from '../schemas/userSchema'; import { ApiError } from '../utils/ApiError';
import { User } from '../schemas/userSchema';
import bcrypt from 'bcryptjs'; import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken'; import jwt from 'jsonwebtoken';
import { clearJwtCookie, setJwtCookie } from '../middlewares/checkAuth'; import { clearJwtCookie, setJwtCookie } from '../middlewares/checkAuth';
const create = async (req: Request, res: Response) => { const create = async (req: Request, res: Response, next) => {
try { try {
const { email, password, address } = req.body; const { email, password, address } = req.body;
const user = await User.create({ email, password, address }); const user = await createUser({
email,
password,
address
});
if(user instanceof ApiError) {
return next(user);
}
res.status(201).json(user); res.status(201).json(user);
} catch(error) { } catch {
res.status(500).json({ error: 'An error occurred during signup' }); const error = new ApiError('Error during user creation');
error.statusCode = 500;
error.status = 'fail';
next(error);
} }
} }
// export async function login(req: Request, res: Response) {
// try {
// const { email, password } = req.body;
// // Check if the user exists const login = async (req: Request, res: Response, next) => {
// const user: IUser | null = await User.findOne({ email }); try {
// if (!user) { const { email, password } = req.body;
// console.error('User not found'); const user: any = await loginUser({
// return res.status(401).json({ error: 'Invalid email or password' }); email,
// } password
});
if(user instanceof ApiError) {
console.log("Error in login")
return res.status(user.statusCode).json({ error: user.message });
}
const payload = {
userId: user._id
}
// Generate a JWT
const token = jwt.sign(payload, process.env.JWT_SECRET as string, { expiresIn: '1d' });
setJwtCookie(res, token);
// Send the JWT as the response
res.status(200).json({
token
});
} catch {
const error = new ApiError('Error during user login');
error.statusCode = 500;
error.status = 'fail';
next(error)
}
}
// // Compare the provided password with the stored password const logout = async (req: Request, res: Response, next) => {
// const isPasswordCorrect = await bcrypt.compare(password, user.password); try {
// if (!isPasswordCorrect) { clearJwtCookie(res);
// console.error('Invalid password'); res.status(200).json({ message: 'Logout successful' });
// return res.status(401).json({ error: 'Invalid email or password' }); } catch {
// } const error = new ApiError('Error during user logout');
error.statusCode = 500;
error.status = 'fail';
next(error);
}
}
// const payload = { const getAll = async (req: Request, res: Response, next) => {
// userId: user._id try {
// } const users = await getAllUsers();
// // Generate a JWT res.status(200).json(users);
// const token = jwt.sign(payload, process.env.JWT_SECRET as string, { expiresIn: '1d' }); } catch {
const error = new ApiError('Error during user retrieval');
error.statusCode = 500;
error.status = 'fail';
next(error);
}
}
// setJwtCookie(res, token); const deleteHandler = async (req: Request, res: Response, next) => {
try {
const { id } = req.params;
const user = await deleteUser(id);
res.status(200).json(user);
} catch {
const error = new ApiError('Error during user deletion');
error.statusCode = 500;
error.status = 'fail';
next(error);
}
}
// // Send the JWT as the response
// res.status(200).json({
// token
// });
// } catch (error) {
// console.error('Error during login:', error);
// res.status(500).json({ error: 'An error occurred during login' });
// }
// }
// export async function logout(req: Request, res: Response) {
// try {
// clearJwtCookie(res);
// res.status(200).json({ message: 'Logout successful' });
// } catch (error) {
// console.error('Error during logout:', error);
// res.status(500).json({ error: 'An error occurred during logout' });
// }
// }
// export async function getAllUsers(req: Request, res: Response) {
// try {
// const users = await User.find().select('-__v -password');
// res.status(200).json({ users });
// } catch (error) {
// console.error('Error getting all users:', error);
// res.status(500).json({ error: 'An error occurred while getting all users' });
// }
// }
// export async function deleteUser(req: Request, res: Response) {
// try {
// const { id } = req.params;
// const user = await User.findByIdAndDelete(id);
// if (!user) {
// return res.status(404).json({ error: 'User not found' });
// }
// res.status(200).json({ message: 'User deleted successfully' });
// } catch (error) {
// console.error('Error deleting user:', error);
// res.status(500).json({ error: 'An error occurred while deleting the user' });
// }
// }
export { export {
create create,
getAll,
logout,
login,
deleteHandler
} }

View file

@ -7,6 +7,8 @@ import productRouter from './routes/productRouter';
import cartRouter from './routes/cartRouter'; import cartRouter from './routes/cartRouter';
import { errorHandler } from './middlewares/errorHandler'; import { errorHandler } from './middlewares/errorHandler';
import { ApiError } from './utils/ApiError';
const env = require('dotenv').config().parsed; const env = require('dotenv').config().parsed;
@ -40,9 +42,9 @@ app.use('/cart', cartRouter);
app.all('*', (req, res, next) => { app.all('*', (req, res, next) => {
// res.status(404).json({ error: 'Route not found' }); // res.status(404).json({ error: 'Route not found' });
const error = new Error('Route not found'); const error = new ApiError('Route not found');
// error.statusCode = 404; error.statusCode = 404;
// error.status = 'fail'; error.status = 'fail';
next(error) next(error)
}); });

View file

@ -1,11 +1,12 @@
const errorHandler = (error, req, res, next) => { const errorHandler = (error, req, res, next) => {
// error.statusCode = error.statusCode || 500; error.statusCode = error.statusCode || 500;
// error.message = error.message || 'Internal server error'; error.message = error.message || 'Internal server error';
// error.status = error.status || 'error'; error.status = error.status || 'error';
res.status(error).json( res.status(error.statusCode).json({
{ status: error.status,
error: error.message statusCode: error.statusCode,
}); message: error.message
});
} }

View file

@ -1,34 +1,98 @@
// import { User, IUser } from "../schemas/userSchema"; import { User, IUser } from "../schemas/userSchema";
// import validate from 'deep-email-validator'; import validate from 'deep-email-validator';
import { ApiError } from "../utils/ApiError";
import { response } from "express";
import bcrypt from 'bcryptjs';
// const createUser = async (user: IUser) => { const createUser = async (user: any) => {
// if (!user.email || !user.password || !user.address) { if (!user.email || !user.password || !user.address) {
// console.log('All inputs are required') const error = new ApiError('Missing required fields');
// } error.statusCode = 400;
error.status = 'fail';
return error;
}
// const { valid, reason, validators } = await validate(user.email); const { valid, reason, validators } = await validate(user.email);
// if (!valid) { if (!valid) {
// // throw new Error(reason); const error = new ApiError(reason);
// console.log(reason) error.statusCode = 400;
error.status = 'fail';
return error;
}
// } const userExists = await User.exists({ email: user.email });
if (userExists) {
const error = new ApiError('User already exists, Try login :)');
error.statusCode = 400;
error.status = 'fail';
return error;
}
// const userExists = await User.exists({ email: user.email }); const salt = await bcrypt.genSalt(10);
// if (userExists) { user.password = await bcrypt.hash(user.password, salt);
// console.log('User already exists, Try login :)')
// }
// const newUser = new User(user);
// try {
// await newUser.save();
// return newUser;
// } catch (error) {
// return error;
// }
// } const newUser = new User(user);
try {
await newUser.save();
return {
email: newUser.email,
address: newUser.address,
};
} catch (error) {
return error;
}
}
// export { const loginUser = async (user: any) => {
// createUser const { email, password } = user;
// } const userExists = await User.findOne({ email });
if (!userExists) {
const error = new ApiError('Invalid email or password');
error.statusCode = 404;
error.status = 'fail';
return error;
}
const isMatch = await bcrypt.compare(password, userExists.password);
if(!isMatch) {
const error = new ApiError('Invalid email or password');
error.statusCode = 404;
error.status = 'fail';
return error;
}
return userExists;
}
const getAllUsers = async () => {
try {
const users = await User.find();
return users;
} catch {
const error = new ApiError('Error during fetching users');
error.statusCode = 500;
error.status = 'fail';
return error;
}
}
const deleteUser = async (id: string) => {
try {
const user = await User.findByIdAndDelete(id);
return user;
} catch {
const error = new ApiError('Error during user deletion');
error.statusCode = 500;
error.status = 'fail';
return error;
}
}
export {
createUser,
loginUser,
getAllUsers,
deleteUser
}

View file

@ -1,12 +1,12 @@
import express from 'express'; import express from 'express';
import { create } from '../controllers/userController'; import { create, login, getAll, deleteHandler } from '../controllers/userController';
const userRouter = express.Router(); const userRouter = express.Router();
userRouter.post('/', create); userRouter.post('/', create);
// userRouter.get('/', getAllUsers); userRouter.get('/', getAll);
// userRouter.post('/login', login); userRouter.post('/login', login);
// userRouter.post('/logout', logout); // userRouter.post('/logout', logout);
// userRouter.delete('/:id', deleteUser) userRouter.delete('/:id', deleteHandler)
export default userRouter; export default userRouter;

View file

@ -4,8 +4,6 @@ interface IUser extends Document {
email: string; email: string;
password: string; password: string;
address: string; address: string;
createdAt: Date;
updatedAt: Date;
} }
const UserSchema: Schema = new Schema({ const UserSchema: Schema = new Schema({

10
src/utils/ApiError.ts Normal file
View file

@ -0,0 +1,10 @@
class ApiError extends Error {
statusCode: number;
status: string;
constructor(message: string) {
super(message);
}
}
export { ApiError };