Create a cart
Cart Action
Header
- Composable Action:
composables/useCart/useCartApi.ts
- API Route:
POST /api/carts
Detailed Description
The createCart
action is a fundamental feature of the cart system that allows creating a new cart.
It plays a central role in cart management by enabling users to:
- Create a new cart
- Initialize cart settings
- Set up cart metadata
- Prepare for product additions
This action is used in several contexts:
- New shopping session
- Cart management
- Order preparation
- Cart synchronization
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: Create new cart C->>UC: createCart(params) UC->>Auth: Check authentication Auth-->>UC: OK UC->>A: POST /api/carts 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 Validation Error A-->>UC: 400 Bad Request UC-->>C: Error C-->>U: Validation message else Server Error A-->>UC: 500 Server Error UC-->>C: Error C-->>U: Error message end
Call Parameters
Main Interface
interface CreateCartRequest {
name?: string; // Optional cart name
currency: string; // Currency for price calculation
type?: CartType; // Optional cart type
}
Detailed Parameters
Parameter | Type | Required | Default Value | Impact |
---|---|---|---|---|
name | string | No | - | Custom cart name |
currency | string | Yes | - | Currency for prices |
type | CartType | No | 'CART' | Cart type |
Call Example
const response = await createCart({
name: 'My Shopping Cart',
currency: 'EUR',
type: 'CART',
});
Composable Returns
Response Interface
interface CreateCartResponse {
success: boolean; // Indicates if creation was successful
message: string; // Confirmation or error message
cart?: Cart; // Created cart details
}
interface Cart {
id: string; // Cart ID
name: string; // Cart name
status: CartStatus; // Cart status
type: CartType; // Cart type
currency: string; // Currency
createdAt: string; // Creation date
updatedAt: string; // Last update date
totalPrice: {
// Total price
amount: number; // Amount
currency: string; // Currency
};
lines: CartLine[]; // Cart lines
}
type CartType = 'CART' | 'BUYING_LIST';
type CartStatus = 'DRAFT' | 'VALIDATED' | 'CANCELLED';
Success Response Format
{
"success": true,
"message": "Cart created successfully",
"cart": {
"id": "cart-123",
"name": "My Shopping Cart",
"status": "DRAFT",
"type": "CART",
"currency": "EUR",
"createdAt": "2024-03-20T10:00:00Z",
"updatedAt": "2024-03-20T10:00:00Z",
"totalPrice": {
"amount": 0,
"currency": "EUR"
},
"lines": []
}
}
Error Handling
Error Types
Code | Cause | Action | Message |
---|---|---|---|
401 | Not authenticated | Login redirect | "Not authenticated" |
400 | Invalid data | Validation message | "Invalid cart data" |
500 | Server error | Error message | "Server error" |
Error Response Format
{
"success": false,
"message": "Specific error message",
"error": {
"statusCode": 400,
"message": "Error details"
}
}
Error Handling Example
try {
const response = await createCart({
name: 'My Shopping Cart',
currency: 'EUR',
});
} catch (error) {
switch (error.statusCode) {
case 401:
router.push('/auth/login');
break;
case 400:
showNotification(error.message, 'error');
break;
default:
showNotification('An error occurred', 'error');
}
}
Use Cases
-
New Shopping Session
- Starting a new cart
- Setting initial parameters
- Preparing for products
-
Cart Management
- Creating multiple carts
- Organizing purchases
- Managing different types
-
Order Preparation
- Initializing orders
- Setting up metadata
- Preparing for checkout
Important Points
Performance
- Quick cart creation
- Efficient store updates
- Response caching
Security
- Authentication required
- Data validation
- Access control
Flexibility
- Multiple cart types
- Currency support
- Custom naming
Integration
- Store synchronization
- Authentication integration
- Notification support
Technical Implementation
/**
* Creates a new cart
* @param params - Request parameters
* @param params.name - Optional cart name
* @param params.currency - Currency
* @param params.type - Optional cart type
* @param useStore - If true, updates the Pinia store
* @returns Promise<CreateCartResponse | null>
* @throws {ApiError} - Error if request fails
*/
export const useCart = () => {
const createCart = async (
params: CreateCartRequest,
useStore = true
): Promise<CreateCartResponse | null> => {
try {
await ensureAuthenticated();
const { data, error } = await useFetch<CreateCartResponse>('/api/carts', {
method: 'POST',
body: params,
key: 'createCart',
});
if (error.value) {
handleError(error.value);
}
if (useStore && data.value) {
updateStore(data.value);
}
return data.value || null;
} catch (e) {
handleError(e);
}
};
return {
createCart,
};
};
Execution Flow
- Authentication Check
await ensureAuthenticated();
- Parameter Validation
if (!params.currency) {
throw new Error('Currency is required');
}
- API Call
const { data, error } = await useFetch<CreateCartResponse>('/api/carts', {
method: 'POST',
body: params,
});
- Response Handling
if (useStore && data.value) {
cartStore.cart = data.value.cart;
}
- Error Handling
if (error.value) {
handleError(error.value);
}
Updated about 2 months ago