Get carts

Cart Action

Header

  • Composable Action: composables/useCart/useCartApi.ts
  • API Route: GET /api/carts

Detailed Description

The fetchCarts action is a core feature of the cart system that allows retrieving a list of carts for the authenticated user. It plays a central role in cart management by enabling users to:

  • View all their carts
  • Filter carts by status
  • Sort carts by date
  • Access cart metadata

This action is used in several contexts:

  • Cart listing
  • Cart management
  • Order tracking
  • 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: View carts list
    C->>UC: fetchCarts(params)
    UC->>Auth: Check authentication
    Auth-->>UC: OK
    UC->>A: GET /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 No Carts
        A-->>UC: Empty list
        UC-->>C: Empty state
        C-->>U: Show empty message
    else Server Error
        A-->>UC: 500 Server Error
        UC-->>C: Error
        C-->>U: Error message
    end

Call Parameters

Main Interface

interface FetchCartsRequest {
  status?: CartStatus[]; // Optional status filter
  sortBy?: string; // Optional sort field
  sortOrder?: 'asc' | 'desc'; // Optional sort order
  page?: number; // Optional page number
  limit?: number; // Optional items per page
}

Detailed Parameters

ParameterTypeRequiredDefault ValueImpact
statusCartStatus[]No-Filter by cart status
sortBystringNo'createdAt'Sort field
sortOrder'asc' | 'desc'No'desc'Sort direction
pagenumberNo1Page number
limitnumberNo10Items per page

Call Example

const response = await fetchCarts({
  status: ['DRAFT', 'VALIDATED'],
  sortBy: 'createdAt',
  sortOrder: 'desc',
  page: 1,
  limit: 10,
});

Composable Returns

Response Interface

interface FetchCartsResponse {
  success: boolean; // Indicates if retrieval was successful
  message: string; // Confirmation or error message
  carts: Cart[]; // List of carts
  pagination: {
    // Pagination information
    total: number; // Total number of carts
    page: number; // Current page
    limit: number; // Items per page
    pages: number; // Total number of pages
  };
}

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": "Carts retrieved successfully",
  "carts": [
    {
      "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": 39.98,
        "currency": "EUR"
      },
      "lines": []
    }
  ],
  "pagination": {
    "total": 1,
    "page": 1,
    "limit": 10,
    "pages": 1
  }
}

Error Handling

Error Types

CodeCauseActionMessage
401Not authenticatedLogin redirect"Not authenticated"
400Invalid parametersValidation message"Invalid parameters"
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 fetchCarts({
    status: ['DRAFT'],
    page: 1,
    limit: 10,
  });
} 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. Cart Listing

    • View all carts
    • Filter by status
    • Sort by date
  2. Cart Management

    • Track cart status
    • Monitor changes
    • Organize carts
  3. Order Tracking

    • View order history
    • Check order status
    • Access order details

Important Points

Performance

  • Pagination support
  • Efficient filtering
  • Response caching

Security

  • Authentication required
  • Data validation
  • Access control

Flexibility

  • Multiple filters
  • Sorting options
  • Pagination control

Integration

  • Store synchronization
  • Authentication integration
  • Notification support

Technical Implementation

/**
 * Retrieves a list of carts
 * @param params - Request parameters
 * @param params.status - Optional status filter
 * @param params.sortBy - Optional sort field
 * @param params.sortOrder - Optional sort order
 * @param params.page - Optional page number
 * @param params.limit - Optional items per page
 * @param useStore - If true, updates the Pinia store
 * @returns Promise<FetchCartsResponse | null>
 * @throws {ApiError} - Error if request fails
 */
export const useCart = () => {
  const fetchCarts = async (
    params: FetchCartsRequest,
    useStore = true
  ): Promise<FetchCartsResponse | null> => {
    try {
      await ensureAuthenticated();

      const { data, error } = await useFetch<FetchCartsResponse>('/api/carts', {
        method: 'GET',
        params,
        key: 'fetchCarts',
      });

      if (error.value) {
        handleError(error.value);
      }

      if (useStore && data.value) {
        updateStore(data.value);
      }

      return data.value || null;
    } catch (e) {
      handleError(e);
    }
  };

  return {
    fetchCarts,
  };
};

Execution Flow

  1. Authentication Check
await ensureAuthenticated();
  1. Parameter Validation
if (params.page && params.page < 1) {
  throw new Error('Page number must be greater than 0');
}
  1. API Call
const { data, error } = await useFetch<FetchCartsResponse>('/api/carts', {
  method: 'GET',
  params,
});
  1. Response Handling
if (useStore && data.value) {
  cartStore.carts = data.value.carts;
  cartStore.pagination = data.value.pagination;
}
  1. Error Handling
if (error.value) {
  handleError(error.value);
}