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

ParameterTypeRequiredDefault ValueImpact
namestringNo-Custom cart name
currencystringYes-Currency for prices
typeCartTypeNo'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

CodeCauseActionMessage
401Not authenticatedLogin redirect"Not authenticated"
400Invalid dataValidation message"Invalid cart data"
500Server errorError 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

  1. New Shopping Session

    • Starting a new cart
    • Setting initial parameters
    • Preparing for products
  2. Cart Management

    • Creating multiple carts
    • Organizing purchases
    • Managing different types
  3. 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

  1. Authentication Check
await ensureAuthenticated();
  1. Parameter Validation
if (!params.currency) {
  throw new Error('Currency is required');
}
  1. API Call
const { data, error } = await useFetch<CreateCartResponse>('/api/carts', {
  method: 'POST',
  body: params,
});
  1. Response Handling
if (useStore && data.value) {
  cartStore.cart = data.value.cart;
}
  1. Error Handling
if (error.value) {
  handleError(error.value);
}