From d1ed7dfbccfcea80f0fb9788f9540aaceb640074 Mon Sep 17 00:00:00 2001 From: Kfir Dayan Date: Wed, 21 Jun 2023 11:53:08 +0300 Subject: [PATCH] added middlware error handler --- src/controllers/ProductController.ts | 4 +- src/controllers/UserController.ts | 165 ++++++++++++--------------- src/index.ts | 18 ++- src/middlewares/errorHandler.ts | 14 +++ src/middlewares/errorHandlers.ts | 18 --- src/models/userModel.ts | 35 +++++- src/routes/userRouter.ts | 14 +-- 7 files changed, 146 insertions(+), 122 deletions(-) create mode 100644 src/middlewares/errorHandler.ts delete mode 100644 src/middlewares/errorHandlers.ts diff --git a/src/controllers/ProductController.ts b/src/controllers/ProductController.ts index abb7c2f..96e793e 100644 --- a/src/controllers/ProductController.ts +++ b/src/controllers/ProductController.ts @@ -1,6 +1,6 @@ import { Request, Response } from 'express'; import { Product } from '../schemas/productSchema'; -import { handleCreateProductError } from '../middlewares/errorHandlers'; +// import { handleCreateProductError } from '../middlewares/errorHandler'; export async function createProduct(req: Request, res: Response) { @@ -10,7 +10,7 @@ export async function createProduct(req: Request, res: Response) { res.json(product); } catch (error) { console.error('Error creating product:', error); - handleCreateProductError(res, error); + // handleCreateProductError(res, error); } } diff --git a/src/controllers/UserController.ts b/src/controllers/UserController.ts index fa36cef..76bd769 100644 --- a/src/controllers/UserController.ts +++ b/src/controllers/UserController.ts @@ -1,111 +1,90 @@ import { Request, Response } from 'express'; +// import { createUser } from '../models/userModel'; +import { IUser } from '../schemas/userSchema'; +import { User } from '../schemas/userSchema'; import bcrypt from 'bcryptjs'; import jwt from 'jsonwebtoken'; -import { User, IUser } from '../schemas/userSchema'; import { clearJwtCookie, setJwtCookie } from '../middlewares/checkAuth'; -import validate from 'deep-email-validator'; -export async function createUser(req: Request, res: Response) { +const create = async (req: Request, res: Response) => { try { const { email, password, address } = req.body; - const isValidEmail = await validate(email); - if (!isValidEmail.valid) { - console.error('Email is invalid:', isValidEmail.validators); - return res.status(400).json({ error: 'Email is invalid' }); - } - - if (!(password && address)) { - return res.status(400).json({ error: 'All inputs are required' }); - } - // checkIfUserExists return true if the user exists - const userExists = await User.exists({ email }); - if(userExists) { - return res.status(400).json({ error: 'User already exists, Try login :)' }); - } - - const hashedPassword = await bcrypt.hash(password, 10); - - const user: IUser = await User.create({ - email, - password: hashedPassword, - address, - }); - - res.status(200).json({ - massage: 'User created successfully' - }); - } catch (error) { - console.error('Error creating user:', error); - res.status(500).json({ error: 'An error occurred while creating the user.' }); + const user = await User.create({ email, password, address }); + res.status(201).json(user); + } catch(error) { + res.status(500).json({ error: 'An error occurred during signup' }); } + } +// export async function login(req: Request, res: Response) { +// try { +// const { email, password } = req.body; -export async function login(req: Request, res: Response) { - try { - const { email, password } = req.body; +// // Check if the user exists +// const user: IUser | null = await User.findOne({ email }); +// if (!user) { +// console.error('User not found'); +// return res.status(401).json({ error: 'Invalid email or password' }); +// } - // Check if the user exists - const user: IUser | null = await User.findOne({ email }); - if (!user) { - console.error('User not found'); - return res.status(401).json({ error: 'Invalid email or password' }); - } +// // Compare the provided password with the stored password +// const isPasswordCorrect = await bcrypt.compare(password, user.password); +// if (!isPasswordCorrect) { +// console.error('Invalid password'); +// return res.status(401).json({ error: 'Invalid email or password' }); +// } - // Compare the provided password with the stored password - const isPasswordCorrect = await bcrypt.compare(password, user.password); - if (!isPasswordCorrect) { - console.error('Invalid password'); - return res.status(401).json({ error: 'Invalid email or password' }); - } +// const payload = { +// userId: user._id +// } +// // Generate a JWT +// const token = jwt.sign(payload, process.env.JWT_SECRET as string, { expiresIn: '1d' }); - const payload = { - userId: user._id - } - // Generate a JWT - const token = jwt.sign(payload, process.env.JWT_SECRET as string, { expiresIn: '1d' }); +// setJwtCookie(res, token); - setJwtCookie(res, token); +// // 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' }); +// } +// } - // 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 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 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 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 { + create } \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index 5a4aa36..d228490 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,6 +6,8 @@ import userRouter from './routes/userRouter'; import productRouter from './routes/productRouter'; import cartRouter from './routes/cartRouter'; +import { errorHandler } from './middlewares/errorHandler'; + const env = require('dotenv').config().parsed; const app = express(); @@ -14,6 +16,9 @@ const PORT = env.PORT || 3000; app.use(express.json()); app.use(cookieParser()) + + + // Connect to MongoDB using Mongoose mongoose.connect(env.DATABASE_URL); @@ -33,7 +38,18 @@ app.use('/users', userRouter); app.use('/products', productRouter); app.use('/cart', cartRouter); +app.all('*', (req, res, next) => { + // res.status(404).json({ error: 'Route not found' }); + const error = new Error('Route not found'); + // error.statusCode = 404; + // error.status = 'fail'; + next(error) +}); + +app.use(errorHandler); + + // Start server -app.listen(PORT, () => { +app.listen(PORT, () => { console.log(`Server started on port ${PORT}`); }); diff --git a/src/middlewares/errorHandler.ts b/src/middlewares/errorHandler.ts new file mode 100644 index 0000000..f2dfc32 --- /dev/null +++ b/src/middlewares/errorHandler.ts @@ -0,0 +1,14 @@ +const errorHandler = (error, req, res, next) => { + // error.statusCode = error.statusCode || 500; + // error.message = error.message || 'Internal server error'; + // error.status = error.status || 'error'; + res.status(error).json( + { + error: error.message + }); + +} + +export { + errorHandler +} \ No newline at end of file diff --git a/src/middlewares/errorHandlers.ts b/src/middlewares/errorHandlers.ts deleted file mode 100644 index 1c39482..0000000 --- a/src/middlewares/errorHandlers.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Request, Response, NextFunction } from 'express'; - - - -export function handleCreateProductError(res: Response, error: Error) { - let statusCode = 500; - let errorMessage = 'An error occurred while creating the product.'; - - if (error.message === 'Missing required fields.') { - statusCode = 400; - errorMessage = 'Missing required fields.'; - } else if (error.message === 'Product already exists.') { - statusCode = 409; - errorMessage = 'Product already exists.'; - } - - res.status(statusCode).json({ error: errorMessage }); -} \ No newline at end of file diff --git a/src/models/userModel.ts b/src/models/userModel.ts index 1d0415c..1ca8879 100644 --- a/src/models/userModel.ts +++ b/src/models/userModel.ts @@ -1 +1,34 @@ -import { User, IUser } from "../schemas/userSchema"; \ No newline at end of file +// import { User, IUser } from "../schemas/userSchema"; +// import validate from 'deep-email-validator'; + + +// const createUser = async (user: IUser) => { + +// if (!user.email || !user.password || !user.address) { +// console.log('All inputs are required') +// } + +// const { valid, reason, validators } = await validate(user.email); +// if (!valid) { +// // throw new Error(reason); +// console.log(reason) + +// } + +// const userExists = await User.exists({ email: user.email }); +// if (userExists) { +// console.log('User already exists, Try login :)') +// } +// const newUser = new User(user); +// try { +// await newUser.save(); +// return newUser; +// } catch (error) { +// return error; +// } + +// } + +// export { +// createUser +// } \ No newline at end of file diff --git a/src/routes/userRouter.ts b/src/routes/userRouter.ts index 98f7e64..129bdad 100644 --- a/src/routes/userRouter.ts +++ b/src/routes/userRouter.ts @@ -1,12 +1,12 @@ import express from 'express'; -import { createUser, login, logout, getAllUsers, deleteUser } from '../controllers/userController'; +import { create } from '../controllers/userController'; const userRouter = express.Router(); -userRouter.post('/', createUser); -userRouter.get('/', getAllUsers); -userRouter.post('/login', login); -userRouter.post('/logout', logout); -userRouter.delete('/:id', deleteUser) - +userRouter.post('/', create); +// userRouter.get('/', getAllUsers); +// userRouter.post('/login', login); +// userRouter.post('/logout', logout); +// userRouter.delete('/:id', deleteUser) + export default userRouter; \ No newline at end of file