Add functionality to remove an item from the cart in cart module

master
nicekid1 2 months ago
parent 81d2629d05
commit b0c858c151
  1. 12
      src/cart/cart.controller.ts
  2. 22
      src/cart/cart.service.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);
}
}

@ -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,
);
}
}
}

Loading…
Cancel
Save