Improve error handling structure in cart module

master
nicekid1 2 months ago
parent 6308630b4b
commit 3591ae9139
  1. 7
      src/cart/cart.controller.ts
  2. 127
      src/cart/cart.service.ts

@ -38,12 +38,9 @@ export class CartController {
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Delete(":productId") @Delete(":productId")
async removeFromCart(@Param("productId") productId: number, @Request() req: any): Promise<{ message: string }> { async removeFromCart(@Param("productId") productId: number, @Request() req: any) {
const userId = req.user.id; const userId = req.user.id;
await this.cartService.removeFromCart(userId, productId); return await this.cartService.removeFromCart(userId, productId);
return {
message: "Product removed from cart successfully",
};
} }
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)

@ -23,41 +23,47 @@ export class CartService {
if (!userId || !productId || !quantity || isNaN(Number(quantity)) || Number(quantity) <= 0) { if (!userId || !productId || !quantity || isNaN(Number(quantity)) || Number(quantity) <= 0) {
throw new HttpException("Invalid parameters: userId, productId, and a positive quantity are required.", HttpStatus.BAD_REQUEST); throw new HttpException("Invalid parameters: userId, productId, and a positive quantity are required.", HttpStatus.BAD_REQUEST);
} }
const product = await this.productModel.findByPk(productId); const product = await this.productModel.findByPk(productId);
if (!product) { if (!product) {
throw new HttpException("Product not found!", HttpStatus.NOT_FOUND); throw new HttpException("Product not found!", HttpStatus.NOT_FOUND);
} }
if (product.quantity < quantity) {
let invoice = await this.invoiceModel.findOne({ where: { userId, status: "pending" } }); throw new HttpException("Product quantity insufficient!", HttpStatus.CONFLICT);
if (!invoice) {
invoice = await this.invoiceService.createInvoiceFromCart(userId);
}
const invoiceId = invoice.id;
let cart = await this.cartModel.findOne({ where: { userId, productId, status: "open" } });
console.log(cart);
if (!cart) {
cart = await this.cartModel.create({
userId,
productId,
invoiceId,
quantity,
productPrice: product.price,
status: "open",
});
await cart.save();
} else {
cart.quantity += Number(quantity);
await cart.save();
} }
try {
let invoice = await this.invoiceModel.findOne({ where: { userId, status: "pending" } });
if (!invoice) {
invoice = await this.invoiceService.createInvoiceFromCart(userId);
}
const invoiceId = invoice.id;
let cart = await this.cartModel.findOne({ where: { userId, productId, status: "open" } });
if (!cart) {
cart = await this.cartModel.create({
userId,
productId,
invoiceId,
quantity,
productPrice: product.price,
status: "open",
});
await cart.save();
} else {
cart.quantity += Number(quantity);
await cart.save();
}
await this.invoiceService.updateTotalPayment(userId); await this.invoiceService.updateTotalPayment(userId);
return { return {
message: cart.id ? "Product quantity updated in cart successfully!" : "Product added to cart successfully!", message: cart.id ? "Product quantity updated in cart successfully!" : "Product added to cart successfully!",
cartItem: cart, cartItem: cart,
}; };
} catch (error) {
console.error("Error during adding item to cart:", error);
throw new HttpException("An unexpected error occurred while adding the product to cart. Please try again later.", HttpStatus.INTERNAL_SERVER_ERROR);
}
} }
// Get user's cart // Get user's cart
async getUserOpenCart(userId: number): Promise<{ cartItems: Cart[]; totalPrice: number }> { async getUserOpenCart(userId: number): Promise<{ cartItems: Cart[]; totalPrice: number }> {
@ -65,49 +71,58 @@ export class CartService {
throw new HttpException("User ID is required.", HttpStatus.BAD_REQUEST); throw new HttpException("User ID is required.", HttpStatus.BAD_REQUEST);
} }
const cartItems = await this.cartModel.findAll({ try {
where: { userId,status:"open" }, const cartItems = await this.cartModel.findAll({
include: [ where: { userId, status: "open" },
{ include: [
model: Product, {
attributes: [], model: Product,
}, attributes: ["name"],
], },
}); ],
});
if (!cartItems || cartItems.length === 0) {
throw new HttpException("No cart items found for the specified user.", HttpStatus.NOT_FOUND); if (!cartItems || cartItems.length === 0) {
} throw new HttpException("No cart items found for the specified user.", HttpStatus.NOT_FOUND);
}
const totalPrice = cartItems.reduce((sum, item) => sum + (Number(item.productPrice * item.quantity) || 0), 0); const totalPrice = cartItems.reduce((sum, item) => sum + (Number(item.productPrice) * item.quantity || 0), 0);
return { cartItems, totalPrice }; return { cartItems, totalPrice };
} catch (error) {
throw new HttpException("An unexpected error occurred while fetching the cart. Please try again later.", HttpStatus.INTERNAL_SERVER_ERROR);
}
} }
// Update cart item quantity // Update cart item quantity
async updateCart(userId: number, productId: number, quantity: number): Promise<Cart> { async updateCart(userId: number, productId: number, quantity: number): Promise<Cart> {
const cartItem = await this.cartModel.findOne({ where: { userId, productId } }); const cartItem = await this.cartModel.findOne({ where: { userId, productId, status: "open" } });
if (!cartItem) { if (!cartItem) {
throw new HttpException("Product not found in the cart.", HttpStatus.NOT_FOUND); throw new HttpException("Product not found in the cart.", HttpStatus.NOT_FOUND);
} }
try {
cartItem.quantity = quantity; cartItem.quantity = quantity;
await cartItem.save(); await cartItem.save();
await this.invoiceService.updateTotalPayment(userId); await this.invoiceService.updateTotalPayment(userId);
return cartItem; return cartItem;
} catch (error) {
throw new HttpException("An unexpected error occurred while updating the cart. Please try again later.", HttpStatus.INTERNAL_SERVER_ERROR);
}
} }
// Remove an item from cart // Remove an item from cart
async removeFromCart(userId: number, productId: number): Promise<{ message: string }> { async removeFromCart(userId: number, productId: number): Promise<{ message: string; cartItem: Cart }> {
const cartItem = await this.cartModel.findOne({ where: { userId, productId } }); const cartItem = await this.cartModel.findOne({ where: { userId, productId, status: "open" } });
if (!cartItem) { if (!cartItem) {
throw new HttpException("Product not found in the cart.", HttpStatus.NOT_FOUND); throw new HttpException("Product not found in the cart.", HttpStatus.NOT_FOUND);
} }
await cartItem.destroy(); try {
await this.invoiceService.updateTotalPayment(userId); await cartItem.destroy();
return { message: "Item deleted from your cart successfully." }; await this.invoiceService.updateTotalPayment(userId);
return { message: "Item deleted from your cart successfully.", cartItem };
} catch (error) {
throw new HttpException("An unexpected error occurred while removing the item from the cart. Please try again later.", HttpStatus.INTERNAL_SERVER_ERROR);
}
} }
//delete whole cart //delete whole cart

Loading…
Cancel
Save