Home > widget-integration > CartService

CartService class

Cart service managing cart operations and business logic

Provides cart functionality including: - Adding products to cart (single or multi-product) - Cart quantity management with queue to prevent race conditions - Cart modal rendering with template customization - Post-add-to-cart action handling (redirect, drawer, etc.) - Cart backup/restore functionality

Extension points for Technical Support customization: - - Custom redirect/drawer behavior after adding items - - Custom cart page redirect logic - - Shop-specific cart rendering defaults - - Custom cart item formatting and enrichment - - Custom cart template loading - - Custom validation rules for cart items - - Add shop-specific data to cart responses - - Custom error handling and user feedback

Signature:

export declare class CartService 

Example 1

Basic usage

const cartService = container.resolve(CartService);

// Add single product
await cartService.addToCart({
  productId: '12345',
  quantity: 2
});

// Add multiple products
await cartService.addToCart({
  items: [
    { id: '12345', quantity: 1 },
    { id: '67890', quantity: 2 }
  ]
});

Example 2

Technical Support customization

class CustomCartService extends CartService {
  // Custom post-add behavior: show notification instead of redirect
  protected async handlePostAddToCartAction(): Promise<void> {
    const { enableCart, cartNotification } = this.appService.themeSettings.cart;

    if (enableCart) {
      // Show cart drawer
      this.showCartDrawer();
    } else if (cartNotification) {
      // Show success notification
      this.showSuccessNotification();
    } else {
      // Default: redirect to cart page
      this.redirectToCartPage();
    }
  }

  // Custom cart item processing: add gift wrapping options
  protected processCartItem(item: Product, showCurrencyCodes: boolean) {
    const processed = super.processCartItem(item, showCurrencyCodes);

    // Add gift wrapping info if available
    if (item.properties?.gift_wrap) {
      processed.giftWrapping = {
        enabled: true,
        message: item.properties.gift_message,
      };
    }

    return processed;
  }

  // Custom validation: enforce minimum order amount
  protected async validateAddToCartItem(item: AddToCartItem): Promise<boolean> {
    const baseValid = await super.validateAddToCartItem(item);
    if (!baseValid) return false;

    const minOrderAmount = this.appService.getConfig().minOrderAmount;
    if (minOrderAmount) {
      const cartData = await this.getCartData();
      const newTotal = cartData.total_price + (item.price * item.quantity);

      if (newTotal < minOrderAmount) {
        this.showMinOrderAmountError(minOrderAmount);
        return false;
      }
    }

    return true;
  }
}

Constructors

Constructor

Modifiers

Description

(constructor)(cartAPI, cartSelectors, appService)

Constructs a new instance of the CartService class

Methods

Method

Modifiers

Description

addToCart(item)

Add product(s) to cart with validation and error handling

Supports both single product and multi-product additions. Handles cart count updates, post-add actions, and error scenarios.

Extension points: - Override to add custom validation rules - Override to customize post-add behavior - Override to customize error handling

changeQuantity(productId, quantity)

Change quantity of a cart item with queue management Business logic method - ensures sequential updates to prevent conflicts

enrichCartData(cartData, addedItem)

protected

Enrich cart data with shop-specific information Override to add custom fields, metadata, or transformations

Common customization scenarios: - Add product recommendations - Include loyalty points information - Add estimated delivery dates - Add gift wrapping options - Add cross-sell/upsell data

getCartData()

Get current cart data Business logic method - handles data retrieval and error handling

getCartItems()

Get all items currently in the cart Returns empty array if cart is empty or on error

getCartTemplate()

protected

Get cart template HTML for rendering Override to provide shop-specific templates or custom template loading logic

Template resolution priority: 1. TAEAppConfig.template.cart (from backend/metafield) - highest priority 2. Local static template file (fallback) - default

The template should use Liquid-compatible syntax and expect these variables: - items: Array of formatted cart items - item_count: Total number of items - items_subtotal_price: Formatted subtotal price - cartStyle: Cart display style ('side', 'modal', etc.) - locale: Current locale path - translations: Translation strings

getCurrentLocale()

protected

Get current Shopify locale from window.Shopify object Override to customize locale detection logic

getDefaultCartConfig()

protected

Get default cart rendering configuration Override to provide shop-specific defaults that differ from standard settings

Default values: - cartStyle: 'side' (side drawer) - showCurrencyCodes: false (hide currency codes)

Common cart style values: - 'side': Side drawer (slides from right) - 'drawer': Bottom drawer - 'modal': Center modal - 'page': Full page redirect

handleCartError(error, errorType, context)

protected

Handle cart operation errors with custom logging and user feedback Override to customize error handling, user notifications, and tracking

Common customization scenarios: - Show user-friendly error messages - Track errors in analytics - Send error notifications to support team - Implement retry logic for transient errors - Trigger fallback behaviors

handlePostAddToCartAction()

protected

Handle post add-to-cart actions (redirect, drawer, notification, etc.) Override to customize behavior after successfully adding items to cart

Common customization scenarios: - Show cart drawer/modal instead of redirect - Display success notification - Trigger upsell/cross-sell modal - Update mini cart display - Track add-to-cart events in analytics

Default behavior: - If cart drawer is enabled: do nothing (let drawer handle it) - If cart drawer is disabled: redirect to cart page

processCartItem(item, showCurrencyCodes)

protected

Process and format cart item for display Override to add shop-specific fields, transformations, or enrichments

Default processing: - Formats price using shop currency settings - Filters out default/empty variant options - Maintains all original item properties

Common customization scenarios: - Add product badges (new, sale, limited) - Include inventory status - Add estimated delivery dates - Format custom properties for display - Add product recommendations - Include subscription information

redirectToCartPage()

protected

Redirect to cart page with proper locale handling Override for custom redirect logic or additional behavior

Common customization scenarios: - Add query parameters to cart URL - Redirect to custom checkout page - Add analytics tracking before redirect - Show loading indicator during redirect

renderCartModal()

Render cart modal HTML with current cart data Fetches cart data, applies formatting, and renders using cart template

Customization points: - - Default rendering settings - - Item formatting and enrichment - - Template source

restoreCartIfNeeded()

Restore cart from localStorage backup if backup exists Handles cart recovery scenarios (after checkout, session restore, etc.)

Process: 1. Check for backup_cart_items in localStorage 2. If found, clear current cart 3. Add all backed up items back to cart 4. Clean up backup (success or failure)

Override to customize backup/restore logic or add validation

safeRedirect(url)

protected

Safely redirect to URL with XSS protection Validates URL is relative path before redirecting to prevent security vulnerabilities

Security features: - Only allows relative URLs starting with / - Blocks protocol-relative URLs (//evil.com) - Blocks javascript:, data:, and other protocol handlers - Blocks absolute URLs to external sites

updateCartIconCount(count)

Update cart icon count in UI Business logic method - updates UI elements with cart count

validateAddToCartItem(item)

protected

Validate cart item before adding to cart Override to implement shop-specific validation rules

Common customization scenarios: - Enforce minimum/maximum quantities - Check inventory availability - Validate custom properties - Apply business rules (subscription eligibility, etc.)