API: Orders
Relevant source files
The following files were used as context for generating this wiki page:
The Orders API is a core component of the e-commerce microservices platform, responsible for managing the entire lifecycle of a customer's order. It handles order creation, retrieval, status updates, and cancellation. The system is designed as a dedicated microservice (order-app) that communicates with other services like the Product, Cart, and Payment services via a NATS message broker. The API Gateway acts as the single entry point for all client requests related to orders, ensuring proper authentication and routing.
Architecture
The Orders feature follows a microservice pattern. A client request first hits the API Gateway, which authenticates the user and forwards the request to the order-app microservice over NATS. The order-app contains all the business logic for managing orders and interacts with its own PostgreSQL database via Prisma.
The diagram below shows the request flow from the client to the order-app and the subsequent event-based communication with other microservices.
API Endpoints
The postman-collection.json file defines the public-facing endpoints for the Orders API, which are exposed through the API Gateway.
| Method | Path | Description | Authentication |
|---|---|---|---|
POST | /orders | Create a new order from cart items. | Bearer Token |
GET | /orders | List all orders for the current user. | Bearer Token |
GET | /orders/:orderId | Get a specific order by its ID. | Bearer Token |
PUT | /orders/:orderId/status | Update the status of an order (Admin only). | Bearer Token |
PUT | /orders/:orderId/cancel | Cancel an order. | Bearer Token |
Sources: postman-collection.json
Data Model
The order data is structured across two main tables: Order and OrderItem. An Order has a one-to-many relationship with OrderItem.
This ER diagram illustrates the database schema for orders and their items.
Order Table Schema
| Field | Type | Description |
|---|---|---|
id | String | Unique identifier for the order. |
userId | String | ID of the user who placed the order. |
addressId | String | ID of the shipping address (can be null). |
status | OrderStatus | The current processing status of the order. See Order Status Lifecycle. |
paymentStatus | PaymentStatus | The current payment status of the order. See Payment Status. |
totalInt | Int | The total cost of the order in integer format (e.g., cents). |
createdAt | DateTime | Timestamp of when the order was created. |
updatedAt | DateTime | Timestamp of the last update. |
| Sources: apps/order-app/src/orders/orders.service.spec.ts:40-67, scripts/seed.ts:168-191 |
OrderItem Table Schema
| Field | Type | Description |
|---|---|---|
id | String | Unique identifier for the order item. |
orderId | String | Foreign key linking to the Order table. |
productId | String | ID of the product. |
productName | String | Name of the product at the time of order. |
imageUrls | String[] | Array of product image URLs. |
quantity | Int | Number of units of the product ordered. |
priceInt | Int | Price per unit in integer format. |
createdAt | DateTime | Timestamp of when the item was added. |
| Sources: apps/order-app/src/orders/orders.service.spec.ts:47-60, scripts/seed.ts:184-188 |
Core Business Logic
Order Creation Flow
Creating an order is a multi-step process that coordinates several microservices to ensure data integrity and consistency.
This sequence diagram details the steps involved in creating a new order.
The creation logic includes:
- Validation: Ensures the order contains at least one item.
- Product Verification: Communicates with the
product-appto verify that all product IDs are valid and have sufficient stock. If not, aValidationRpcExceptionis thrown. - Total Calculation: The total price is calculated based on the quantity and price of each item.
- Database Transaction: A new
Orderand its associatedOrderItemrecords are created within a single database transaction to ensure atomicity. - Stock Decrement: An event (
EVENTS.PRODUCT.DEC_STOCK) is emitted to theproduct-appto decrement the stock for the purchased products. - Cart Clearing: An event (
EVENTS.CART.CLEAR) is emitted to thecart-appto clear the user's shopping cart.
Sources: apps/order-app/src/orders/orders.service.spec.ts:200-290
Order Status Lifecycle
Orders progress through a defined set of statuses. The updateStatus method enforces valid transitions between states.
This state diagram shows the possible transitions for an order's status.
PENDING: The initial state of an order after creation.PROCESSING: The order is being prepared for shipment.SHIPPED: The order has been dispatched.DELIVERED: The order has been delivered to the customer.CANCELLED: The order has been cancelled.
When an order is transitioned to CANCELLED, the service emits an EVENTS.PRODUCT.INC_STOCK event to the product-app to restore the stock levels of the items in the cancelled order.
Sources: apps/order-app/src/orders/orders.service.spec.ts:650-665
Payment Status
The paymentStatus field tracks the financial state of the order.
UNPAID: The default status. For Cash on Delivery (COD) orders, it remainsUNPAIDuntil confirmed.PAID: The order has been successfully paid for.REFUNDED: The payment for the order has been refunded.
The updatePaymentStatus endpoint is used by the payment service or an administrator to update this status.
Sources: apps/order-app/src/orders/orders.service.spec.ts:223, 1109-1131, scripts/seed.ts:182
Order Item Management
While items are primarily added during order creation, the OrderItemService allows for modifications to an existing order, such as adding or removing items.
addItem: Adds a new item to an order and updates the order'stotalIntwithin a database transaction.removeItem: Removes an item from an order and decrements the order'stotalInt.
Sources: apps/order-app/src/order-item/order-item.service.spec.ts:100-200
Error Handling
The order-app uses specific RPC exceptions to provide clear error information back to the gateway and the client.
| Exception | Description | Example Scenario |
|---|---|---|
EntityNotFoundRpcException | Thrown when a requested resource (e.g., an order) does not exist. | Calling GET /orders/non-existent-id. |
ValidationRpcException | Thrown for input validation failures or business rule violations. | Creating an order with insufficient product stock. |
ConflictRpcException | Thrown when an action conflicts with the current state of a resource. | Attempting to cancel an order that is already cancelled. |
InternalServerRpcException | Thrown for unexpected database errors or other internal failures. | A database transaction fails unexpectedly. |
| Sources: apps/order-app/src/orders/orders.service.spec.ts, apps/order-app/src/order-item/order-item.service.spec.ts |
Conclusion
The Orders API is a robust and central part of the e-commerce platform, designed with a clear separation of concerns using a microservice architecture. It manages the complete order lifecycle, from creation and validation against product inventory to status tracking and cancellation. Its event-driven communication with other services like Product and Cart ensures data consistency across the distributed system, while its well-defined API and error handling provide a reliable interface for client applications.