API: Cart
Relevant source files
The following files were used as context for generating this wiki page:The Cart API provides functionalities for managing a user's shopping cart. It is a core component of the e-commerce platform, designed as a microservice (cart-app) that communicates with other parts of the system, such as the API Gateway and the Product service, via a NATS message broker. The API handles creating carts, adding/updating/removing items, and retrieving cart contents.
The system follows a Perimeter Security Pattern, where the API Gateway is responsible for authentication and authorization, while the cart-app microservice trusts incoming requests from the gateway. All cart-related endpoints require user authentication via a JWT Bearer token.
Sources: README.md, apps/gateway/REFACTORING-GUIDE.md, apps/gateway/src/cart/cart.controller.ts:15-16
Architecture and Data Flow
The cart functionality is split between the API Gateway and the cart-app microservice. The Gateway exposes the public-facing REST API, while the cart-app contains the business logic and database interactions.
- A client sends an HTTP request to a
/cartendpoint on the API Gateway. - The
AuthGuardon the Gateway verifies the user's JWT. - The
CartControllerin the Gateway receives the request, extracts the user ID from the token, and sends a message to thecart-appvia NATS. - The
CartControllerin thecart-appreceives the message and calls theCartService. - The
CartServiceperforms the business logic, interacting with its own PostgreSQL database via Prisma. - For operations that require product details (like getting the cart total), the
CartServicesends a message to theproduct-appvia NATS to fetch product information. - The final response is sent back through NATS to the Gateway, which then returns it to the client.
Sources: apps/gateway/REFACTORING-GUIDE.md, apps/cart-app/src/cart/cart.service.spec.ts:121-127, apps/gateway/src/cart/cart.controller.ts:24-27
System Interaction Diagram
This diagram illustrates the sequence of operations when a user requests their cart.
API Endpoints
All endpoints are prefixed with /cart and require authentication. The user's identity is automatically extracted from the JWT token.
Sources: postman-collection.json, apps/gateway/src/cart/cart.controller.ts
Get Cart
Retrieves the current user's cart. If a cart doesn't exist for the user, a new one is created.
| Property | Description |
|---|---|
| Method | GET |
| Path | /cart |
| Authentication | Required (Bearer Token) |
| Response (200 OK) | CartResponse object containing the cart, enriched items, and total price. |
Sources: postman-collection.json, apps/gateway/src/cart/cart.controller.ts:24-27
Add Item to Cart
Adds a product to the cart. If the item already exists, its quantity is increased.
| Property | Description |
|---|---|
| Method | POST |
| Path | /cart/items |
| Authentication | Required (Bearer Token) |
| Request Body | AddItemToCartDto |
| Response (201 Created) | CartResponse object with the updated cart state. |
AddItemToCartDto
| Field | Type | Description |
|---|---|---|
productId | string | The ID of the product to add. |
quantity | number | The quantity to add. Must be greater than 0. |
Sources: postman-collection.json, apps/gateway/src/cart/cart.controller.ts:33-36, apps/cart-app/src/cart/cart.service.spec.ts:308-319
Update Cart Item
Updates the quantity of an item in the cart. Setting the quantity to 0 will remove the item.
| Property | Description |
| --- | --- | --- |
| Method | PATCH |
| Path | /cart/items |
| Authentication | Required (Bearer Token) |
| Request Body | UpdateCartItemDto |
| Response (200 OK) | CartResponse object with the updated cart state. |
UpdateCartItemDto
| Field | Type | Description |
|---|---|---|
productId | string | The ID of the product to update. |
quantity | number | The new quantity. Must be a non-negative integer. |
Sources: postman-collection.json, apps/gateway/src/cart/cart.controller.ts:42-45, apps/cart-app/src/cart/cart.service.spec.ts:430-441
Remove Item from Cart
Removes a specific product entirely from the cart, regardless of its quantity.
| Property | Description |
| --- | --- | --- |
| Method | DELETE |
| Path | /cart/items |
| Authentication | Required (Bearer Token) |
| Request Body | RemoveFromCartDto |
| Response (200 OK) | CartResponse object with the updated cart state. |
RemoveFromCartDto
| Field | Type | Description |
|---|---|---|
productId | string | The ID of the product to remove. |
Sources: postman-collection.json, apps/gateway/src/cart/cart.controller.ts:51-57
Clear Cart
Removes all items from the user's cart.
| Property | Description |
| --- | --- | --- |
| Method | DELETE |
| Path | /cart |
| Authentication | Required (Bearer Token) |
| Response (200 OK) | SuccessResponse object, e.g., { "success": true }. |
Sources: postman-collection.json, apps/gateway/src/cart/cart.controller.ts:63-66
Core Logic (cart-app)
The CartService in the cart-app microservice orchestrates all business logic.
Sources: apps/cart-app/src/cart/cart.service.spec.ts
Key CartService Methods
getOrCreateCart(dto): Finds a cart byuserIdorsessionId. If a cart is found without auserIdbut auserIdis provided, it updates the cart to associate it with the user. If no cart is found, it creates a new one.get(dto): The main method to retrieve a cart. It callsgetOrCreateCart, then if the cart has items, it callsfetchProductsByIdsto get product data from theproduct-app. Finally, it enriches the cart items with product details and calculates the total price.addItem(dto): Validates thatquantity > 0. It gets or creates a cart and then uses Prisma'supserton thecartItemmodel to either create a new item or add to the existing quantity.updateItem(dto): Ifquantityis0, it callsremoveItem. Otherwise, it updates the quantity of the specified item in the cart.removeItem(dto): Deletes acartItemfrom the database based oncartIdandproductId.clear(userId): Finds the user's cart and deletes all associatedcartItems.
Sources: apps/cart-app/src/cart/cart.service.spec.ts:137-150, 194-200, 308-319, 372-383, 452-463, 488-500
Database Schema
The database schema can be inferred from the Prisma client mocks in the service tests.
This diagram shows the relationship between the Cart and CartItem entities.
Sources: apps/cart-app/src/cart/cart.service.spec.ts:16-36, 90-101
Error Handling
The CartService implements robust error handling by wrapping underlying errors in specific RPC exceptions, which are then propagated to the API Gateway.
| Exception | Trigger | Message Example |
|---|---|---|
ValidationRpcException | quantity is 0 or negative when adding/updating. | Số lượng phải lớn hơn 0 |
EntityNotFoundRpcException | Cart not found when trying to clear it. | Cart not found |
ServiceUnavailableRpcException | The product-app microservice call times out. | Product service is unavailable |
InternalServerRpcException | Unexpected database errors or other unhandled exceptions. | Lỗi khi lấy thông tin giỏ hàng |
Sources: apps/cart-app/src/cart/cart.service.spec.ts:164-171, 311-328, 503-509
Summary
The Cart API is a well-defined module within the microservices architecture. It effectively separates concerns by having the API Gateway handle HTTP and authentication, while the cart-app microservice manages the core business logic. Its asynchronous communication with the product-app via NATS allows for a decoupled and scalable system. The comprehensive error handling ensures that issues from downstream services are managed gracefully.