From 3591ae91397347e53a449b00c390aa63d3264e68 Mon Sep 17 00:00:00 2001 From: nicekid1 <86746988+nicekid1@users.noreply.github.com> Date: Wed, 8 Jan 2025 16:01:28 +0330 Subject: [PATCH] Improve error handling structure in cart module --- src/cart/cart.controller.ts | 7 +- src/cart/cart.service.ts | 127 ++++++++++++++++++++---------------- 2 files changed, 73 insertions(+), 61 deletions(-) diff --git a/src/cart/cart.controller.ts b/src/cart/cart.controller.ts index 4cc0884..7650774 100644 --- a/src/cart/cart.controller.ts +++ b/src/cart/cart.controller.ts @@ -38,12 +38,9 @@ export class CartController { @UseGuards(JwtAuthGuard) @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; - await this.cartService.removeFromCart(userId, productId); - return { - message: "Product removed from cart successfully", - }; + return await this.cartService.removeFromCart(userId, productId); } @UseGuards(JwtAuthGuard) diff --git a/src/cart/cart.service.ts b/src/cart/cart.service.ts index a47e1d1..0aa51f4 100644 --- a/src/cart/cart.service.ts +++ b/src/cart/cart.service.ts @@ -23,41 +23,47 @@ export class CartService { 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); } - const product = await this.productModel.findByPk(productId); if (!product) { throw new HttpException("Product not found!", HttpStatus.NOT_FOUND); } - - 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" } }); - 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(); + if (product.quantity < quantity) { + throw new HttpException("Product quantity insufficient!", HttpStatus.CONFLICT); } + 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 { - message: cart.id ? "Product quantity updated in cart successfully!" : "Product added to cart successfully!", - cartItem: cart, - }; + return { + message: cart.id ? "Product quantity updated in cart successfully!" : "Product added to cart successfully!", + 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 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); } - const cartItems = await this.cartModel.findAll({ - where: { userId,status:"open" }, - include: [ - { - model: Product, - attributes: [], - }, - ], - }); - - if (!cartItems || cartItems.length === 0) { - throw new HttpException("No cart items found for the specified user.", HttpStatus.NOT_FOUND); - } + try { + const cartItems = await this.cartModel.findAll({ + where: { userId, status: "open" }, + include: [ + { + model: Product, + attributes: ["name"], + }, + ], + }); + + 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 async updateCart(userId: number, productId: number, quantity: number): Promise { - const cartItem = await this.cartModel.findOne({ where: { userId, productId } }); - + const cartItem = await this.cartModel.findOne({ where: { userId, productId, status: "open" } }); if (!cartItem) { throw new HttpException("Product not found in the cart.", HttpStatus.NOT_FOUND); } - - cartItem.quantity = quantity; - await cartItem.save(); - await this.invoiceService.updateTotalPayment(userId); - return cartItem; + try { + cartItem.quantity = quantity; + await cartItem.save(); + await this.invoiceService.updateTotalPayment(userId); + 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 - async removeFromCart(userId: number, productId: number): Promise<{ message: string }> { - const cartItem = await this.cartModel.findOne({ where: { userId, productId } }); - + async removeFromCart(userId: number, productId: number): Promise<{ message: string; cartItem: Cart }> { + const cartItem = await this.cartModel.findOne({ where: { userId, productId, status: "open" } }); if (!cartItem) { throw new HttpException("Product not found in the cart.", HttpStatus.NOT_FOUND); } - await cartItem.destroy(); - await this.invoiceService.updateTotalPayment(userId); - return { message: "Item deleted from your cart successfully." }; + try { + await cartItem.destroy(); + 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