ecomm/__tests__/controllers/CartController.test.ts

75 lines
2 KiB
TypeScript
Raw Normal View History

2023-06-13 13:10:17 +00:00
import { Request, Response } from 'express';
import { Cart, ICart, Order } from '../mongoose/Schema.test';
import { config } from 'dotenv';
config();
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 | null = 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');
}
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.' });
}
}
export async function checkout(req: Request, res: Response) {
const { userId } = req.body;
const usersCart = await Cart.findOne({ userId });
if (!usersCart) {
res.status(404).json({ error: 'Cart not found.' });
return;
}
const order = await Order.create({
userId,
products: usersCart.products,
});
await removeCart(userId);
// sendEmailasync(order.id, userId);
res.status(200).json(order);
}
async function removeCart(userId: string) {
await Cart.deleteOne({ userId });
}