done with cart
This commit is contained in:
parent
a5fc4bd03c
commit
0583ba5f51
5 changed files with 89 additions and 5 deletions
50
src/controllers/CartController.ts
Normal file
50
src/controllers/CartController.ts
Normal file
|
@ -0,0 +1,50 @@
|
|||
import { Request, Response } from 'express';
|
||||
import { Cart, ICart } from '../mongoose/Schema';
|
||||
|
||||
export async function addToCart(req: Request, res: Response) {
|
||||
try {
|
||||
const { userId, productId } = req.body;
|
||||
if (!productId) {
|
||||
res.status(400).json({ error: 'Product id is required.' });
|
||||
return;
|
||||
}
|
||||
let cart: ICart = await Cart.findOne({ userId });
|
||||
if (!cart) {
|
||||
cart = await Cart.create({
|
||||
userId,
|
||||
products: { [productId]: 1 },
|
||||
});
|
||||
} else {
|
||||
const currentQuantity = cart.products[productId];
|
||||
if (currentQuantity === undefined) {
|
||||
cart.products[productId] = 1;
|
||||
} else {
|
||||
cart.products[productId] += 1;
|
||||
}
|
||||
cart.markModified('products'); // Mark 'products' field as modified
|
||||
}
|
||||
|
||||
await cart.save();
|
||||
res.status(200).json(cart);
|
||||
} catch (error) {
|
||||
console.error('Error adding product to cart:', error);
|
||||
res.status(500).json({ error: 'An error occurred while adding the product to the cart.' });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
export async function listCart(req: Request, res: Response) {
|
||||
try {
|
||||
const { userId } = req.body;
|
||||
const cart = await Cart.findOne({ userId });
|
||||
if (!cart) {
|
||||
res.status(404).json({ error: 'Cart not found.' });
|
||||
return;
|
||||
}
|
||||
res.status(200).json(cart.products);
|
||||
} catch (error) {
|
||||
console.error('Error listing cart:', error);
|
||||
res.status(500).json({ error: 'An error occurred while listing the cart.' });
|
||||
}
|
||||
}
|
|
@ -4,6 +4,10 @@ import { Product, IProduct } from '../mongoose/Schema';
|
|||
export async function createProduct(req: Request, res: Response) {
|
||||
try {
|
||||
const { name, description, price, userId } = req.body;
|
||||
if(!name || !description || !price || !userId) {
|
||||
res.status(400).json({ error: 'Name, description, price and user id are required.' });
|
||||
return;
|
||||
}
|
||||
const product: IProduct = await Product.create({
|
||||
name,
|
||||
description,
|
||||
|
@ -32,5 +36,3 @@ export async function listProducts(req: Request, res: Response) {
|
|||
res.status(500).json({ error: 'An error occurred while listing the products.' });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
|
|
@ -4,6 +4,7 @@ import cookieParser from 'cookie-parser';
|
|||
|
||||
import userRouter from './routes/user';
|
||||
import productRouter from './routes/product';
|
||||
import cartRouter from './routes/cart';
|
||||
|
||||
const env = require('dotenv').config().parsed;
|
||||
|
||||
|
@ -20,7 +21,10 @@ mongoose.connect(env.DATABASE_URL);
|
|||
const db = mongoose.connection;
|
||||
|
||||
// Check for DB connection
|
||||
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
|
||||
db.on('error', () => {
|
||||
console.error.bind(console, 'MongoDB connection error:')
|
||||
process.exit(1);
|
||||
});
|
||||
db.once('open', () => {
|
||||
console.log('Connected to MongoDB');
|
||||
});
|
||||
|
@ -28,6 +32,7 @@ db.once('open', () => {
|
|||
// Routes
|
||||
app.use('/users', userRouter);
|
||||
app.use('/products', productRouter);
|
||||
app.use('/cart', cartRouter);
|
||||
|
||||
// Start server
|
||||
app.listen(PORT, () => {
|
||||
|
|
|
@ -19,6 +19,13 @@ export interface IProduct extends Document {
|
|||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export interface ICart extends Document {
|
||||
userId: string;
|
||||
products: { [itemId: string]: number };
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
const UserSchema: Schema = new Schema({
|
||||
firstName: { type: String, required: true },
|
||||
lastName: { type: String, required: true },
|
||||
|
@ -38,9 +45,17 @@ const ProductSchema: Schema = new Schema({
|
|||
updatedAt: { type: Date, default: Date.now },
|
||||
});
|
||||
|
||||
const CartSchema: Schema = new Schema({
|
||||
userId: { type: Schema.Types.ObjectId, ref: 'User', required: true, unique: true },
|
||||
products: { type: Schema.Types.Mixed, default: {} },
|
||||
createdAt: { type: Date, default: Date.now },
|
||||
updatedAt: { type: Date, default: Date.now },
|
||||
});
|
||||
|
||||
ProductSchema.index({ name: 1, userId: 1 }, { unique: true });
|
||||
|
||||
const User = mongoose.model<IUser>('User', UserSchema);
|
||||
const Product = mongoose.model<IProduct>('Product', ProductSchema);
|
||||
const Cart = mongoose.model<ICart>('Cart', CartSchema);
|
||||
|
||||
export { User, Product };
|
||||
export { User, Product, Cart };
|
||||
|
|
12
src/routes/cart.ts
Normal file
12
src/routes/cart.ts
Normal file
|
@ -0,0 +1,12 @@
|
|||
import express, { Request } from 'express';
|
||||
import { authenticateToken } from '../middlewares/checkAuth';
|
||||
import { addToCart, listCart } from '../controllers/CartController';
|
||||
|
||||
|
||||
|
||||
const cartRouter = express.Router();
|
||||
|
||||
cartRouter.post('/', authenticateToken, addToCart);
|
||||
cartRouter.get('/', authenticateToken, listCart);
|
||||
|
||||
export default cartRouter;
|
Loading…
Reference in a new issue