Compare commits
No commits in common. "d1ed7dfbccfcea80f0fb9788f9540aaceb640074" and "b59e652c9b6b80e9fc66f423006bfa9fdd61dfe2" have entirely different histories.
d1ed7dfbcc
...
b59e652c9b
14 changed files with 127 additions and 152 deletions
BIN
.DS_Store
vendored
BIN
.DS_Store
vendored
Binary file not shown.
|
@ -1,7 +1,7 @@
|
||||||
import { Request, Response } from 'express';
|
import { Request, Response } from 'express';
|
||||||
import { Cart, ICart } from '../schemas/cartSchema';
|
import { Cart, ICart } from '../schemas/cartModel';
|
||||||
import { Product } from '../schemas/productSchema';
|
import { Product } from '../schemas/productModel';
|
||||||
import { Order } from '../schemas/orderSchema';
|
import { Order } from '../schemas/orderModel';
|
||||||
import { sendEmailasync } from '../services/sendGrid';
|
import { sendEmailasync } from '../services/sendGrid';
|
||||||
import { config } from 'dotenv';
|
import { config } from 'dotenv';
|
||||||
|
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
import { Request, Response } from 'express';
|
import { Request, Response } from 'express';
|
||||||
import { Product } from '../schemas/productSchema';
|
import { Product } from '../schemas/productModel';
|
||||||
// import { handleCreateProductError } from '../middlewares/errorHandler';
|
import { handleCreateProductError } from '../middlewares/errorHandlers';
|
||||||
|
|
||||||
|
|
||||||
export async function createProduct(req: Request, res: Response) {
|
export async function createProduct(req: Request, res: Response) {
|
||||||
|
@ -10,7 +10,7 @@ export async function createProduct(req: Request, res: Response) {
|
||||||
res.json(product);
|
res.json(product);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error creating product:', error);
|
console.error('Error creating product:', error);
|
||||||
// handleCreateProductError(res, error);
|
handleCreateProductError(res, error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -1,90 +1,111 @@
|
||||||
import { Request, Response } from 'express';
|
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 bcrypt from 'bcryptjs';
|
||||||
import jwt from 'jsonwebtoken';
|
import jwt from 'jsonwebtoken';
|
||||||
|
import { User, IUser } from '../schemas/userModel';
|
||||||
import { clearJwtCookie, setJwtCookie } from '../middlewares/checkAuth';
|
import { clearJwtCookie, setJwtCookie } from '../middlewares/checkAuth';
|
||||||
|
import validate from 'deep-email-validator';
|
||||||
|
|
||||||
const create = async (req: Request, res: Response) => {
|
export async function createUser(req: Request, res: Response) {
|
||||||
try {
|
try {
|
||||||
const { email, password, address } = req.body;
|
const { email, password, address } = req.body;
|
||||||
const user = await User.create({ email, password, address });
|
const isValidEmail = await validate(email);
|
||||||
res.status(201).json(user);
|
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) {
|
} catch (error) {
|
||||||
res.status(500).json({ error: 'An error occurred during signup' });
|
console.error('Error creating user:', error);
|
||||||
|
res.status(500).json({ error: 'An error occurred while creating the user.' });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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' });
|
||||||
}
|
}
|
||||||
// export async function login(req: Request, res: Response) {
|
|
||||||
// try {
|
|
||||||
// const { email, password } = req.body;
|
|
||||||
|
|
||||||
// // Check if the user exists
|
// Compare the provided password with the stored password
|
||||||
// const user: IUser | null = await User.findOne({ email });
|
const isPasswordCorrect = await bcrypt.compare(password, user.password);
|
||||||
// if (!user) {
|
if (!isPasswordCorrect) {
|
||||||
// console.error('User not found');
|
console.error('Invalid password');
|
||||||
// return res.status(401).json({ error: 'Invalid email or password' });
|
return res.status(401).json({ error: 'Invalid email or password' });
|
||||||
// }
|
}
|
||||||
|
|
||||||
// // Compare the provided password with the stored password
|
const payload = {
|
||||||
// const isPasswordCorrect = await bcrypt.compare(password, user.password);
|
userId: user._id
|
||||||
// if (!isPasswordCorrect) {
|
}
|
||||||
// console.error('Invalid password');
|
// Generate a JWT
|
||||||
// return res.status(401).json({ error: 'Invalid email or password' });
|
const token = jwt.sign(payload, process.env.JWT_SECRET as string, { expiresIn: '1d' });
|
||||||
// }
|
|
||||||
|
setJwtCookie(res, token);
|
||||||
// const payload = {
|
|
||||||
// userId: user._id
|
// Send the JWT as the response
|
||||||
// }
|
res.status(200).json({
|
||||||
// // Generate a JWT
|
token
|
||||||
// const token = jwt.sign(payload, process.env.JWT_SECRET as string, { expiresIn: '1d' });
|
});
|
||||||
|
} catch (error) {
|
||||||
// setJwtCookie(res, token);
|
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
|
|
||||||
// });
|
export async function logout(req: Request, res: Response) {
|
||||||
// } catch (error) {
|
try {
|
||||||
// console.error('Error during login:', error);
|
clearJwtCookie(res);
|
||||||
// res.status(500).json({ error: 'An error occurred during login' });
|
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' });
|
export async function getAllUsers(req: Request, res: Response) {
|
||||||
// } catch (error) {
|
try {
|
||||||
// console.error('Error during logout:', error);
|
const users = await User.find().select('-__v -password');
|
||||||
// res.status(500).json({ error: 'An error occurred during logout' });
|
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 });
|
export async function deleteUser(req: Request, res: Response) {
|
||||||
// } catch (error) {
|
try {
|
||||||
// console.error('Error getting all users:', error);
|
const { id } = req.params;
|
||||||
// res.status(500).json({ error: 'An error occurred while getting all users' });
|
const user = await User.findByIdAndDelete(id);
|
||||||
// }
|
if (!user) {
|
||||||
// }
|
return res.status(404).json({ error: 'User not found' });
|
||||||
|
}
|
||||||
// export async function deleteUser(req: Request, res: Response) {
|
res.status(200).json({ message: 'User deleted successfully' });
|
||||||
// try {
|
} catch (error) {
|
||||||
// const { id } = req.params;
|
console.error('Error deleting user:', error);
|
||||||
// const user = await User.findByIdAndDelete(id);
|
res.status(500).json({ error: 'An error occurred while deleting the user' });
|
||||||
// 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
|
|
||||||
}
|
}
|
16
src/index.ts
16
src/index.ts
|
@ -6,8 +6,6 @@ import userRouter from './routes/userRouter';
|
||||||
import productRouter from './routes/productRouter';
|
import productRouter from './routes/productRouter';
|
||||||
import cartRouter from './routes/cartRouter';
|
import cartRouter from './routes/cartRouter';
|
||||||
|
|
||||||
import { errorHandler } from './middlewares/errorHandler';
|
|
||||||
|
|
||||||
const env = require('dotenv').config().parsed;
|
const env = require('dotenv').config().parsed;
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
|
@ -16,9 +14,6 @@ const PORT = env.PORT || 3000;
|
||||||
app.use(express.json());
|
app.use(express.json());
|
||||||
app.use(cookieParser())
|
app.use(cookieParser())
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// Connect to MongoDB using Mongoose
|
// Connect to MongoDB using Mongoose
|
||||||
mongoose.connect(env.DATABASE_URL);
|
mongoose.connect(env.DATABASE_URL);
|
||||||
|
|
||||||
|
@ -38,17 +33,6 @@ app.use('/users', userRouter);
|
||||||
app.use('/products', productRouter);
|
app.use('/products', productRouter);
|
||||||
app.use('/cart', cartRouter);
|
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
|
// Start server
|
||||||
app.listen(PORT, () => {
|
app.listen(PORT, () => {
|
||||||
console.log(`Server started on port ${PORT}`);
|
console.log(`Server started on port ${PORT}`);
|
||||||
|
|
|
@ -1,14 +0,0 @@
|
||||||
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
|
|
||||||
}
|
|
18
src/middlewares/errorHandlers.ts
Normal file
18
src/middlewares/errorHandlers.ts
Normal file
|
@ -0,0 +1,18 @@
|
||||||
|
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 });
|
||||||
|
}
|
|
@ -1,34 +0,0 @@
|
||||||
// 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
|
|
||||||
// }
|
|
|
@ -1,12 +1,12 @@
|
||||||
import express from 'express';
|
import express from 'express';
|
||||||
import { create } from '../controllers/userController';
|
import { createUser, login, logout, getAllUsers, deleteUser } from '../controllers/userController';
|
||||||
|
|
||||||
const userRouter = express.Router();
|
const userRouter = express.Router();
|
||||||
|
|
||||||
userRouter.post('/', create);
|
userRouter.post('/', createUser);
|
||||||
// userRouter.get('/', getAllUsers);
|
userRouter.get('/', getAllUsers);
|
||||||
// userRouter.post('/login', login);
|
userRouter.post('/login', login);
|
||||||
// userRouter.post('/logout', logout);
|
userRouter.post('/logout', logout);
|
||||||
// userRouter.delete('/:id', deleteUser)
|
userRouter.delete('/:id', deleteUser)
|
||||||
|
|
||||||
export default userRouter;
|
export default userRouter;
|
|
@ -1,6 +1,6 @@
|
||||||
import { config } from "dotenv";
|
import { config } from "dotenv";
|
||||||
import { Order } from "../schemas/orderSchema";
|
import { Order } from "../schemas/orderModel";
|
||||||
import { User } from "../schemas/userSchema";
|
import { User } from "../schemas/userModel";
|
||||||
import client from '@sendgrid/mail';
|
import client from '@sendgrid/mail';
|
||||||
config();
|
config();
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue