Get product Variants

The getProductVariants function retrieves a paginated list of product variants for a specific product identified by its SKU. This function is essential for products that have multiple variations (such as different colors, sizes, or configurations) and enables the application to display all available options to users.

Product variants represent different configurations or variations of a base product, each with unique attributes like color, size, material, or technical specifications. This function supports pagination to handle products with large numbers of variants efficiently, ensuring optimal performance even for complex product catalogs.

The function is particularly important for e-commerce scenarios where customers need to choose from multiple product options, compare variant specifications, or view variant-specific pricing and availability.

Process Flow

sequenceDiagram
    participant User as User
    participant Component as Vue Component
    participant useProduct as useProduct
    participant SDK as Djust SDK
    participant API as API Server
    participant Auth as Auth Service

    User->>Component: Request Product Variants
    Component->>useProduct: getProductVariants(params)

    useProduct->>useProduct: Validate SKU Parameter
    useProduct->>SDK: useFetch('/api/product-variants/{sku}')

    SDK->>Auth: Verify Authentication Token
    Auth-->>SDK: Token Valid

    SDK->>API: GET /api/product-variants/{productSku}

    alt Success Response
        API-->>SDK: 200 - Variants List
        SDK-->>useProduct: GetProductVariantsResponse
        useProduct->>useProduct: Process Pagination
        useProduct-->>Component: Paginated Variants
        Component-->>User: Display Variant Options
    else No Variants Found
        API-->>SDK: 404 - No Variants
        SDK-->>useProduct: Empty Response
        useProduct->>useProduct: Log No Variants
        useProduct-->>Component: Empty Variants List
        Component-->>User: "No variants available"
    else Authentication Error
        Auth-->>SDK: 401 - Unauthorized
        SDK-->>useProduct: Auth Error
        useProduct-->>Component: Authentication Error
        Component-->>User: Redirect to Login
    else Server Error
        API-->>SDK: 500 - Internal Error
        SDK-->>useProduct: Server Error
        useProduct->>useProduct: Log Server Error
        useProduct-->>Component: Error Response
        Component-->>User: "Unable to load variants"
    end

Call Parameters

The function accepts a GetProductVariantsRequest object with the following structure:

GetProductVariantsRequest Interface (from SDK)

interface GetProductVariantsRequest {
  productSku: string;
  locale?: string;
  pageable?: Pageable;
}

interface Pageable {
  page?: number;
  size?: number;
}

Parameter Details

ParameterTypeRequiredDefaultExampleBusiness Impact
productSkustring✅ Yes-"LAPTOP-BASE-001"Critical: Base product SKU for variant lookup
localestring❌ OptionalRuntime config"en-GB", "fr-FR"Localization: Affects variant names and descriptions
pageable.pagenumber❌ Optional00, 1, 2Performance: Controls result pagination
pageable.sizenumber❌ OptionalRuntime config10, 20, 50Performance: Limits variants per request

Complete Example Call

const variantsParams: GetProductVariantsRequest = {
  productSku: "LAPTOP-DELL-BASE",
  locale: "en-GB",
  pageable: {
    page: 0,
    size: 20,
  },
};

const response = await getProductVariants(variantsParams);

Returns from Composable

The function returns a GetProductVariantsResponse object with the following structure:

GetProductVariantsResponse Interface (from SDK)

interface GetProductVariantsResponse {
  success: boolean;
  variants: ProductVariantsPage;
}

interface ProductVariantsPage {
  content: ProductVariant[];
  pageable: Pageable;
  totalElements: number;
  totalPages: number;
  size: number;
  number: number;
  first: boolean;
  last: boolean;
}

interface ProductVariant {
  id: string;
  skuProduct: string;
  skuVariant: string;
  default: boolean;
  status: string;
  info: ProductVariantInfo;
  attributeValues: ProductAttributeValue[];
  productPictures: ProductPicture[];
  mainImageUrl: string;
  gtin: string;
  ean: string;
  externalId: string;
}

interface ProductVariantInfo {
  name: string;
  description: string;
  sku: string;
  mpn: string;
  ean: string;
}

Realistic Example JSON Response

{
  "success": true,
  "variants": {
    "content": [
      {
        "id": "variant-001",
        "skuProduct": "LAPTOP-DELL-BASE",
        "skuVariant": "LAPTOP-DELL-16GB-SILVER",
        "default": true,
        "status": "ACTIVE",
        "info": {
          "name": "Dell Latitude 5520 - 16GB RAM - Silver",
          "description": "Professional laptop with 16GB RAM in silver finish",
          "sku": "LAPTOP-DELL-16GB-SILVER",
          "mpn": "LAT5520-16-SLV",
          "ean": "1234567890123"
        },
        "attributeValues": [
          {
            "attribute": {
              "externalId": "RAM_SIZE",
              "type": "METRIC",
              "label": "RAM Size"
            },
            "value": {
              "selectedValue": 16,
              "unit": "GB"
            }
          },
          {
            "attribute": {
              "externalId": "COLOR",
              "type": "LIST_COLOR",
              "label": "Color"
            },
            "value": [
              {
                "label": "Silver",
                "hexCode": "#C0C0C0"
              }
            ]
          }
        ],
        "productPictures": [
          {
            "urls": [
              {
                "url": "https://cdn.example.com/variants/laptop-dell-silver-main.jpg",
                "width": 800,
                "height": 600
              }
            ],
            "isMain": true,
            "type": "VARIANT_IMAGE"
          }
        ],
        "mainImageUrl": "https://cdn.example.com/variants/laptop-dell-silver-thumb.jpg",
        "gtin": "01234567890123",
        "ean": "1234567890123",
        "externalId": "EXT-VARIANT-001"
      },
      {
        "id": "variant-002",
        "skuProduct": "LAPTOP-DELL-BASE",
        "skuVariant": "LAPTOP-DELL-32GB-BLACK",
        "default": false,
        "status": "ACTIVE",
        "info": {
          "name": "Dell Latitude 5520 - 32GB RAM - Black",
          "description": "Professional laptop with 32GB RAM in black finish",
          "sku": "LAPTOP-DELL-32GB-BLACK",
          "mpn": "LAT5520-32-BLK",
          "ean": "1234567890124"
        },
        "attributeValues": [
          {
            "attribute": {
              "externalId": "RAM_SIZE",
              "type": "METRIC",
              "label": "RAM Size"
            },
            "value": {
              "selectedValue": 32,
              "unit": "GB"
            }
          },
          {
            "attribute": {
              "externalId": "COLOR",
              "type": "LIST_COLOR",
              "label": "Color"
            },
            "value": [
              {
                "label": "Black",
                "hexCode": "#000000"
              }
            ]
          }
        ],
        "productPictures": [
          {
            "urls": [
              {
                "url": "https://cdn.example.com/variants/laptop-dell-black-main.jpg",
                "width": 800,
                "height": 600
              }
            ],
            "isMain": true,
            "type": "VARIANT_IMAGE"
          }
        ],
        "mainImageUrl": "https://cdn.example.com/variants/laptop-dell-black-thumb.jpg",
        "gtin": "01234567890124",
        "ean": "1234567890124",
        "externalId": "EXT-VARIANT-002"
      }
    ],
    "pageable": {
      "page": 0,
      "size": 20
    },
    "totalElements": 8,
    "totalPages": 1,
    "size": 20,
    "number": 0,
    "first": true,
    "last": true
  }
}

Error Management

HTTP Error Codes and Handling

Error CodeCauseSystem ActionUser MessageReturn Format
400Invalid product SKU or pagination parametersLog validation error, return empty response"Invalid product information"{ success: false, variants: null }
401Authentication token missing/invalidTrigger re-authentication flow"Please log in to view variants"Authentication redirect
404No variants found for product SKULog not found, return empty list"No product variations available"{ success: true, variants: { content: [] } }
412Precondition failed (business rules)Log business rule violation"Product variants access restricted"{ success: false, variants: null }
500Internal server errorLog server error, return empty response"Unable to load product variants"{ success: false, variants: null }

Error Handling Example Code

// Global error handling in composable
const getProductVariants = async ({
  productSku,
  locale,
  pageable,
}: GetProductVariantsRequest): Promise<GetProductVariantsResponse | null> => {
  try {
    // Parameter validation
    if (!productSku?.trim()) {
      console.error("Product SKU is required for variants lookup");
      return null;
    }

    const { data, error } = await useFetch<GetProductVariantsResponse>(
      `/api/product-variants/${productSku}`,
      {
        method: "GET",
        params: {
          locale,
          page: pageable?.page,
          size: pageable?.size,
        },
      }
    );

    if (error.value) {
      console.error("Failed to fetch product variants:", {
        productSku,
        error: error.value,
      });
      return null;
    }

    return data.value || null;
  } catch (err) {
    console.error("Unexpected error while fetching product variants:", err);
    return null;
  }
};

// Component-level error handling
const handleVariantsFetch = async (productSku: string) => {
  try {
    const response = await getProductVariants({
      productSku,
      pageable: { page: 0, size: 20 },
    });

    if (!response?.success || !response.variants) {
      throw new Error("Variants not available");
    }

    // Process successful response
    productVariants.value = response.variants.content;
    totalVariants.value = response.variants.totalElements;
  } catch (error) {
    // User notification
    useToast().add({
      title: "Loading Error",
      description: "Unable to load product variations",
      color: "yellow",
    });

    // Fallback to empty state
    productVariants.value = [];
    totalVariants.value = 0;
  }
};

Use Cases

1. Product Configuration Selection

Display all available variants to allow users to select their preferred product configuration.

Scenario: User views product detail page and needs to choose variant (color, size, specs). Parameters: { productSku: baseProduct.sku, pageable: { page: 0, size: 50 } } Expected Outcome: All product variants displayed with attribute differences highlighted.

2. Inventory Check Across Variants

Validate availability and stock levels across all product variants for procurement decisions.

Scenario: Business user checks stock availability for bulk ordering or inventory planning. Parameters: { productSku: product.sku, locale: userLocale.value } Expected Outcome: Variant list with availability status and stock indicators.

3. Comparison View

Enable side-by-side comparison of different product variants to assist purchase decisions.

Scenario: User activates comparison mode to evaluate variant differences and pricing. Parameters: { productSku: selectedProduct.sku, pageable: { page: 0, size: 10 } } Expected Outcome: Structured variant data optimized for comparison table display.

4. Progressive Loading

Load variants in batches for products with large numbers of variations to optimize performance.

Scenario: Product with 100+ variants needs progressive loading for better user experience. Parameters: { productSku: complexProduct.sku, pageable: { page: currentPage, size: 20 } } Expected Outcome: Paginated variant loading with smooth infinite scroll or pagination controls.

Important Points

Performance Considerations

  • Pagination Strategy: Always use appropriate page sizes to balance performance and user experience
  • Caching Optimization: Nuxt caches variant responses to reduce redundant API calls
  • Image Loading: Variant images should be lazy-loaded to prevent initial page performance impact
  • Attribute Processing: Complex attribute types (METRIC, LIST_COLOR) require additional processing overhead

Security Aspects

  • Authentication Validation: Variant access controlled through same authentication as product access
  • Permission Filtering: Backend filters variants based on user's access permissions
  • Input Validation: Product SKU validated to prevent injection attacks
  • Data Privacy: Sensitive variant information filtered based on user role

Flexibility Features

  • Locale Support: Variant names and descriptions adapt to user's language preferences
  • Configurable Pagination: Page size adapts to application requirements and device capabilities
  • Attribute Extensibility: Supports new attribute types without breaking existing functionality
  • Status Filtering: Backend can filter variants by status (ACTIVE, DISCONTINUED, etc.)

Integration Capabilities

  • Composable Integration: Works seamlessly with useProductVariant getters for data processing
  • Offer Integration: Variant data structure compatible with pricing and offer systems
  • Cart Integration: Variant information structured for easy cart and checkout integration
  • Search Integration: Variant attributes can be used for product filtering and search

Technical Implementation

Composable Function with Complete JSDoc

/**
 * Retrieves paginated list of product variants for a given product SKU
 *
 * @param params - Product variants request parameters
 * @param params.productSku - Base product SKU to get variants for
 * @param params.locale - Locale for internationalized variant content
 * @param params.pageable - Pagination configuration
 * @returns Promise resolving to paginated variants response or null
 *
 * @example
 * ```typescript
 * const { getProductVariants } = useProduct();
 *
 * const response = await getProductVariants({
 *   productSku: "LAPTOP-BASE-001",
 *   locale: "en-GB",
 *   pageable: { page: 0, size: 20 }
 * });
 *
 * if (response?.success) {
 *   console.log('Variants found:', response.variants.totalElements);
 *   response.variants.content.forEach(variant => {
 *     console.log('Variant:', variant.info.name);
 *   });
 * }
 * ```
 *
 * @throws {Error} When network request fails or invalid SKU provided
 * @since 1.0.0
 */
const getProductVariants = async ({
  productSku,
  locale,
  pageable,
}: GetProductVariantsRequest): Promise<GetProductVariantsResponse | null> => {
  try {
    // Parameter validation
    if (!productSku?.trim()) {
      throw new Error("Product SKU is required for variants lookup");
    }

    // Runtime configuration for defaults
    const runtimeConfig = useRuntimeConfig();
    const defaultLocale = locale || runtimeConfig.public.locale;
    const defaultPageSize =
      pageable?.size ||
      Number(runtimeConfig.public.defaultPaginationSize) ||
      20;

    const { data, error } = await useFetch<GetProductVariantsResponse>(
      `/api/product-variants/${productSku}`,
      {
        method: "GET",
        params: {
          locale: defaultLocale,
          page: pageable?.page || 0,
          size: defaultPageSize,
        },
        // Enable caching with unique key
        key: `product-variants-${productSku}-${defaultLocale}-${
          pageable?.page || 0
        }-${defaultPageSize}`,
        // Default response structure
        default: () => ({
          success: false,
          variants: null,
        }),
      }
    );

    if (error.value) {
      console.error("Failed to fetch product variants:", {
        productSku,
        locale: defaultLocale,
        pageable,
        error: error.value,
      });
      return null;
    }

    return data.value || null;
  } catch (err) {
    console.error("Unexpected error while fetching product variants:", err);
    return null;
  }
};

Execution Flow

Step-by-Step Process

  1. Parameter Validation

    // Validate required product SKU
    if (!productSku?.trim()) {
      throw new Error("Product SKU is required for variants lookup");
    }
  2. Configuration Setup

    // Apply runtime defaults
    const runtimeConfig = useRuntimeConfig();
    const effectiveLocale = locale || runtimeConfig.public.locale;
    const effectivePageSize =
      pageable?.size || Number(runtimeConfig.public.defaultPaginationSize);
  3. Request Construction

    // Build API request with pagination
    const requestUrl = `/api/product-variants/${productSku}`;
    const requestParams = {
      locale: effectiveLocale,
      page: pageable?.page || 0,
      size: effectivePageSize,
    };
  4. Network Request Execution

    // Execute paginated fetch
    const { data, error } = await useFetch<GetProductVariantsResponse>(
      requestUrl,
      {
        method: "GET",
        params: requestParams,
      }
    );
  5. Response Processing

    // Handle response and errors
    if (error.value) {
      logError("Failed to fetch variants", { productSku, error: error.value });
      return null;
    }
  6. Data Validation

    // Validate response structure
    if (!data.value?.variants?.content) {
      console.warn("No variants content in response");
      return { success: true, variants: { content: [], totalElements: 0 } };
    }
  7. Return Processed Response

    // Return structured variants data
    return {
      success: true,
      variants: data.value.variants,
    };