Get cart informations
Cart Action
Header
- Composable Action:
composables/useCart/useCartApi.ts - API Route:
GET /api/carts/[cartId]
Detailed Description
The getCartById action is a core feature of the cart system that allows retrieving detailed
information about a specific cart. It plays a central role in cart management by enabling users to:
- View cart details
- Check cart status
- Verify cart contents
- Access cart metadata
This action is used in several contexts:
- Cart user interface
- Order management
- Cart synchronization
- Cart state management
Note: When the Shipping module is enabled (shippingEnabled: true), shipping fees are recomputed from the shipping price matrix on every cart read, so the returned amounts always reflect the current matrix and the current shipping address. Blocking or informational conditions (missing reference, inactive shipping type, price change) are surfaced throughblockedLineInformation. See How Shipping Fees Are Calculated at Checkout.
Process Flow
sequenceDiagram
participant U as User
participant C as Vue Component
participant UC as useCart
participant S as Pinia Store
participant A as API
participant Auth as Auth Service
U->>C: View cart details
C->>UC: getCartById(params)
UC->>Auth: Check authentication
Auth-->>UC: OK
UC->>A: GET /api/carts/[cartId]
A-->>UC: Response
UC->>S: Update store
S-->>C: State updated
C-->>U: UI updated
alt Authentication Error
Auth-->>UC: 401 Unauthorized
UC-->>C: Error
C-->>U: Login redirect
else Cart Not Found
A-->>UC: 404 Not Found
UC-->>C: Error
C-->>U: Cart not found message
else Server Error
A-->>UC: 500 Server Error
UC-->>C: Error
C-->>U: Error message
end
Call Parameters
Main Interface
interface GetCartByIdRequest {
cartId: string; // Cart ID
currency: string; // Currency for price calculation
}Detailed Parameters
| Parameter | Type | Required | Default Value | Impact |
|---|---|---|---|---|
| cartId | string | Yes | - | Identifies the cart to retrieve |
| currency | string | Yes | - | Currency for price calculations |
Call Example
const response = await getCartById({
cartId: 'cart-123',
currency: 'EUR',
});Composable Returns
Response Interface
interface GetCartByIdResponse {
success: boolean; // Indicates if the retrieval was successful
message: string; // Confirmation or error message
cart?: Cart; // Cart details
}
interface Cart {
id: string; // Cart ID
status: CartStatus; // Cart status
createdAt: string; // Creation date
updatedAt: string; // Last update date
totalPrice: {
// Total price
amount: number; // Amount
currency: string; // Currency
};
lines: CartLine[]; // Cart lines
}
interface CartLine {
id: string; // Line ID
offerPriceId: string; // Offer ID
quantity: number; // Quantity
price: {
// Offer price
amount: number; // Amount
currency: string; // Currency
};
}
type CartStatus = 'DRAFT' | 'VALIDATED' | 'CANCELLED';Success Response Format
{
"success": true,
"message": "Cart retrieved successfully",
"cart": {
"id": "cart-123",
"status": "DRAFT",
"createdAt": "2024-03-20T10:00:00Z",
"updatedAt": "2024-03-20T10:00:00Z",
"totalPrice": {
"amount": 39.98,
"currency": "EUR"
},
"lines": [
{
"id": "line-123",
"offerPriceId": "offer-456",
"quantity": 2,
"price": {
"amount": 19.99,
"currency": "EUR"
}
}
]
}
}Error Handling
Error Types
| Code | Cause | Action | Message |
|---|---|---|---|
| 401 | Not authenticated | Login redirect | "Not authenticated" |
| 404 | Cart not found | Carts redirect | "Cart not found" |
| 500 | Server error | Error message | "Server error" |
Error Response Format
{
"success": false,
"message": "Specific error message",
"error": {
"statusCode": 404,
"message": "Error details"
}
}Error Handling Example
try {
const response = await getCartById({
cartId: 'cart-123',
currency: 'EUR',
});
} catch (error) {
switch (error.statusCode) {
case 401:
router.push('/auth/login');
break;
case 404:
router.push('/carts');
break;
default:
showNotification('An error occurred', 'error');
}
}Use Cases
-
Cart Details
- Viewing cart information
- Checking cart status
- Accessing cart metadata
-
Order Management
- Order preparation
- Price verification
- Status tracking
-
Cart Synchronization
- Multi-device sync
- Session management
- State updates
Important Points
Performance
- Optimized Pinia store updates
- Efficient error handling
- Response caching
Security
- Authentication verification
- Data validation
- Access control
Flexibility
- Currency support
- Error case handling
- Business needs adaptation
Integration
- Compatible with existing cart system
- Authentication system integration
- Notification system support
Technical Implementation
/**
* Retrieves a cart by its ID
* @param params - Request parameters
* @param params.cartId - Cart ID
* @param params.currency - Currency
* @param useStore - If true, updates the Pinia store
* @returns Promise<GetCartByIdResponse | null>
* @throws {ApiError} - Error if request fails
*/
export const useCart = () => {
const getCartById = async (
params: GetCartByIdRequest,
useStore = true
): Promise<GetCartByIdResponse | null> => {
try {
await ensureAuthenticated();
const { data, error } = await useFetch<GetCartByIdResponse>(`/api/carts/${params.cartId}`, {
method: 'GET',
params: {
currency: params.currency,
},
key: `getCartById-${params.cartId}`,
});
if (error.value) {
handleError(error.value);
}
if (useStore && data.value) {
updateStore(data.value);
}
return data.value || null;
} catch (e) {
handleError(e);
}
};
return {
getCartById,
};
};Execution Flow
- Authentication Check
await ensureAuthenticated();- Parameter Validation
if (!params.cartId || !params.currency) {
throw new Error('Invalid parameters');
}- API Call
const { data, error } = await useFetch<GetCartByIdResponse>(`/api/carts/${params.cartId}`, {
method: 'GET',
params: {
currency: params.currency,
},
});- Response Handling
if (useStore && data.value) {
cartStore.cart = data.value.cart;
}- Error Handling
if (error.value) {
handleError(error.value);
}Updated 28 days ago
Did this page help you?

