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

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

ParameterTypeRequiredDefault ValueImpact
cartIdstringYes-Identifies the cart to retrieve
currencystringYes-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

CodeCauseActionMessage
401Not authenticatedLogin redirect"Not authenticated"
404Cart not foundCarts redirect"Cart not found"
500Server errorError 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

  1. Cart Details

    • Viewing cart information
    • Checking cart status
    • Accessing cart metadata
  2. Order Management

    • Order preparation
    • Price verification
    • Status tracking
  3. 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

  1. Authentication Check
await ensureAuthenticated();
  1. Parameter Validation
if (!params.cartId || !params.currency) {
  throw new Error('Invalid parameters');
}
  1. API Call
const { data, error } = await useFetch<GetCartByIdResponse>(`/api/carts/${params.cartId}`, {
  method: 'GET',
  params: {
    currency: params.currency,
  },
});
  1. Response Handling
if (useStore && data.value) {
  cartStore.cart = data.value.cart;
}
  1. Error Handling
if (error.value) {
  handleError(error.value);
}