diff --git a/src/cart/cart.controller.ts b/src/cart/cart.controller.ts index 3c4395f..d4fe1eb 100644 --- a/src/cart/cart.controller.ts +++ b/src/cart/cart.controller.ts @@ -11,8 +11,16 @@ export class CartController { const result = await this.cartService.addToCart(userId, productId, quantity); return result; } - @Get(':userId') - async getUserCart(@Param('userId') userId: number) { + @Get(":userId") + async getUserCart(@Param("userId") userId: number) { return this.cartService.getUserCart(userId); } + + @Delete(":userId/:productId") + async removeFromCart( + @Param("userId") userId: number, + @Param("productId") productId: number, + ): Promise<{ message: string }> { + return this.cartService.removeFromCart(userId, productId); + } } diff --git a/src/cart/cart.service.ts b/src/cart/cart.service.ts index 2c3168d..577431b 100644 --- a/src/cart/cart.service.ts +++ b/src/cart/cart.service.ts @@ -76,4 +76,26 @@ export class CartService { throw new HttpException("An error occurred while retrieving the cart.", HttpStatus.INTERNAL_SERVER_ERROR); } } + + async removeFromCart(userId: number, productId: number): Promise<{ message: string }> { + try { + const cartItem = await this.cartModel.findOne({ where: { userId, productId } }); + + if (!cartItem) { + throw new HttpException('Product not found in the cart.', HttpStatus.NOT_FOUND); + } + + await cartItem.destroy(); + return { message: 'Item deleted from your cart successfully.' }; + } catch (error) { + if (error instanceof HttpException) { + throw error; + } + + throw new HttpException( + 'An error occurred while removing the product from the cart.', + HttpStatus.INTERNAL_SERVER_ERROR, + ); + } + } }