diff --git a/src/controllers/CartController.ts b/src/controllers/CartController.ts new file mode 100644 index 0000000..86186ec --- /dev/null +++ b/src/controllers/CartController.ts @@ -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.' }); + } +} diff --git a/src/controllers/ProductController.ts b/src/controllers/ProductController.ts index c194e5c..59e8261 100644 --- a/src/controllers/ProductController.ts +++ b/src/controllers/ProductController.ts @@ -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.' }); } } - - diff --git a/src/index.ts b/src/index.ts index cd07542..20d830c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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, () => { diff --git a/src/mongoose/Schema.ts b/src/mongoose/Schema.ts index 7eb5892..c225ee3 100644 --- a/src/mongoose/Schema.ts +++ b/src/mongoose/Schema.ts @@ -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 }, @@ -33,7 +40,14 @@ const ProductSchema: Schema = new Schema({ name: { type: String, required: true }, description: { type: String, required: true }, price: { type: Number, required: true }, - userId: { type: Schema.Types.ObjectId, ref: 'User' , required: true}, + userId: { type: Schema.Types.ObjectId, ref: 'User', required: true }, + createdAt: { type: Date, default: Date.now }, + 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 }, }); @@ -42,5 +56,6 @@ ProductSchema.index({ name: 1, userId: 1 }, { unique: true }); const User = mongoose.model('User', UserSchema); const Product = mongoose.model('Product', ProductSchema); +const Cart = mongoose.model('Cart', CartSchema); -export { User, Product }; +export { User, Product, Cart }; diff --git a/src/routes/cart.ts b/src/routes/cart.ts new file mode 100644 index 0000000..c307fde --- /dev/null +++ b/src/routes/cart.ts @@ -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; \ No newline at end of file