Get product by Id

The getProductbyId function serves as the primary method for retrieving detailed product information by its identifier. This function acts as the cornerstone of product data access within the application, enabling components to fetch comprehensive product details including basic information, attributes, media assets, and related metadata.

The function supports multiple identifier types (SKU, ID, External ID) and provides localization support, making it flexible for various use cases across the e-commerce platform. It integrates seamlessly with the Nuxt 3 SSR capabilities and the Djust SDK to ensure optimal performance and data consistency.

This function is crucial for product detail pages, search results, cart items, and any component that requires complete product information rather than just summary data.

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 Details
    Component->>useProduct: getProductbyId(params)

    useProduct->>useProduct: Validate Parameters
    useProduct->>SDK: useFetch('/api/product/{id}', params)

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

    SDK->>API: GET /api/product/{productId}

    alt Success Response
        API-->>SDK: 200 - Product Data
        SDK-->>useProduct: GetProductResponse
        useProduct->>useProduct: Process Response
        useProduct-->>Component: Formatted Product
        Component-->>User: Display Product Details
    else Product Not Found
        API-->>SDK: 404 - Not Found
        SDK-->>useProduct: Error Response
        useProduct->>useProduct: Log Error
        useProduct-->>Component: Empty Response
        Component-->>User: "Product not found" Message
    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: "Server error" Message
    end

Call Parameters

The function accepts a GetProductRequest object with the following structure:

GetProductRequest Interface (from SDK)

interface GetProductRequest {
  productIdentifier: string;
  productIdType?: ProductIdType;
  locale?: string;
}

type ProductIdType = "EXTERNAL_ID" | "SKU" | "ID";

Parameter Details

Parameter

Type

Required

Default

Example

Business Impact

productIdentifier

string

✅ Yes


"PROD-001", "ABC123"

Critical: Product identifier for data retrieval

productIdType

ProductIdType

❌ Optional

"EXTERNAL_ID"

"SKU", "ID"

Important: Determines lookup strategy and performance

locale

string

❌ Optional

Runtime config

"en-GB", "fr-FR"

Localization: Affects product name, description language

Complete Example Call

const productParams: GetProductRequest = {
  productIdentifier: "LAPTOP-DELL-001",
  productIdType: "SKU",
  locale: "en-GB",
};

const response = await getProductbyId(productParams);

Returns from Composable

The function returns a GetProductResponse object with the following complete structure:

GetProductResponse Interface (from SDK)

interface GetProductResponse {
  success: boolean;
  product: Product;
}

interface Product {
  id: string;
  externalId: string;
  externalSource: string;
  productStatus: ProductStatus;
  attributeValues: ProductAttributeValue[];
  productPictures: ProductPicture[];
  tags: ProductTag[];
  info: ProductInfo;
  createdAt: string;
  updatedAt: string;
}

interface ProductInfo {
  sku: string;
  name: string;
  description: string;
  brand: string;
  unit: ProductUnit;
}

interface ProductAttributeValue {
  attribute: ProductAttribute;
  value: any;
}

interface ProductPicture {
  urls: MediaInfoDTO[];
  isMain: boolean;
  type: string;
}

Realistic Example JSON Response

{
  "success": true,
  "product": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "externalId": "LAPTOP-DELL-001",
    "externalSource": "ERP_SYSTEM",
    "productStatus": "ACTIVE",
    "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/products/laptop-dell-001-main.jpg",
            "width": 800,
            "height": 600
          }
        ],
        "isMain": true,
        "type": "PRODUCT_IMAGE"
      }
    ],
    "tags": [
      {
        "name": "Electronics",
        "category": "PRODUCT_CATEGORY"
      }
    ],
    "info": {
      "sku": "LAPTOP-DELL-001",
      "name": "Dell Latitude 5520 Laptop",
      "description": "Professional laptop with Intel i7 processor",
      "brand": "Dell",
      "unit": {
        "type": "UNIT",
        "unit": "piece"
      }
    },
    "createdAt": "2024-01-15T10:30:00Z",
    "updatedAt": "2024-01-20T14:45:00Z"
  }
}

Error Management

HTTP Error Codes and Handling

Error CodeCauseSystem ActionUser MessageReturn Format
400Invalid product identifier or parametersLog validation error, return empty response"Invalid product information provided"{ success: false, product: null }
401Authentication token missing/invalidTrigger re-authentication flow"Please log in to view product details"Authentication redirect
404Product not found in systemLog not found error, return empty response"Product not available"{ success: false, product: null }
412Precondition failed (business rules)Log business rule violation"Product access restricted"{ success: false, product: null }
500Internal server errorLog server error, return empty response"Technical error, please try again"{ success: false, product: null }

Error Handling Example Code

// Global error handling in composable
const getProductbyId = async (
  params: GetProductRequest
): Promise<GetProductResponse> => {
  try {
    const { data, error } = await useFetch<GetProductResponse>(
      `/api/product/${params.productIdentifier}`,
      {
        params: {
          productIdType: params.productIdType,
          locale: params.locale,
        },
        method: "GET",
      }
    );

    if (error.value) {
      console.error("Failed to fetch product:", error.value);

      // Return structured empty response
      return {
        success: false,
        product: null,
      } as GetProductResponse;
    }

    return data.value as GetProductResponse;
  } catch (error) {
    console.error("Unexpected error occurred:", error);

    // Return safe fallback
    return {
      success: false,
      product: null,
    } as GetProductResponse;
  }
};

// Component-level error handling
const handleProductFetch = async (productId: string) => {
  try {
    const response = await getProductbyId({
      productIdentifier: productId,
    });

    if (!response.success || !response.product) {
      throw new Error("Product not available");
    }

    // Process successful response
    productData.value = response.product;
  } catch (error) {
    // User notification
    useToast().add({
      title: "Error",
      description: "Unable to load product details",
      color: "red",
    });

    // Navigation fallback
    await navigateTo("/products");
  }
};

Use Cases

1. Product Detail Page Display

Load complete product information for dedicated product pages including specifications, images, and attributes.

Scenario: User navigates to product detail page via direct link or search results.
Parameters: { productIdentifier: route.params.productId, productIdType: "EXTERNAL_ID" } Expected Outcome: Full product data displayed with images, description, specifications, and pricing.

2. Quick Product Preview

Fetch product details for modals, popups, or hover previews without full page navigation.

Scenario: User hovers over product card or clicks quick preview button.
Parameters: { productIdentifier: product.sku, productIdType: "SKU" } Expected Outcome: Essential product information shown in overlay without page refresh.

3. Cart Item Validation

Verify product availability and current details when user adds items to cart or during checkout.

Scenario: User adds product to cart or proceeds to checkout with existing cart items.
Parameters: { productIdentifier: cartItem.productSku, productIdType: "SKU" } Expected Outcome: Current product status confirmed, prices updated if changed.

4. Internationalized Product Access

Retrieve product information in user's preferred language for localized experiences.

Scenario: User switches language or accesses product from different locale.
Parameters: { productIdentifier: "PROD-001", locale: userLocale.value } Expected Outcome: Product name, description displayed in user's selected language.

Important Points

Performance Considerations

  • Caching Strategy: Nuxt automatically caches GET requests, reducing API calls for frequently accessed products
  • Pagination Awareness: Function optimized for single product retrieval; use bulk endpoints for multiple products
  • Image Lazy Loading: Product images should be loaded progressively to improve initial page load times
  • SSR Optimization: Function works seamlessly with server-side rendering for better SEO and initial load performance

Security Aspects

  • Authentication Validation: All requests include JWT token validation on server side
  • Input Sanitization: Product identifiers are validated to prevent injection attacks
  • Permission Checking: Backend verifies user has access to requested product data
  • Data Masking: Sensitive product information filtered based on user permissions

Flexibility Features

  • Multiple ID Types: Supports various identifier formats (SKU, External ID, Internal ID) for integration flexibility
  • Locale Support: Full internationalization support for global e-commerce operations
  • Configurable Defaults: Runtime configuration provides sensible defaults for optional parameters
  • Extensible Response: Product data structure supports additional fields without breaking changes

Integration Capabilities

  • SDK Abstraction: Clean separation between UI logic and API communication through SDK layer
  • Type Safety: Full TypeScript support ensures compile-time validation of data structures
  • Error Propagation: Consistent error handling pattern allows components to respond appropriately
  • Composable Architecture: Function can be used independently or as part of larger product management workflows

Technical Implementation

Composable Function with Complete JSDoc

/**
 * Retrieves detailed product information by identifier
 *
 * @param params - Product request parameters
 * @param params.productIdentifier - Product identifier (SKU, ID, External ID)
 * @param params.productIdType - Type of identifier used for lookup
 * @param params.locale - Locale for internationalized content
 * @returns Promise resolving to product response with success status
 *
 * @example
 * ```typescript
 * const { getProductbyId } = useProduct();
 *
 * const response = await getProductbyId({
 *   productIdentifier: "LAPTOP-001",
 *   productIdType: "SKU",
 *   locale: "en-GB"
 * });
 *
 * if (response.success) {
 *   console.log('Product:', response.product.info.name);
 * }
 * ```
 *
 * @throws {Error} When network request fails or invalid parameters provided
 * @since 1.0.0
 */
const getProductbyId = async ({
  productIdentifier,
  productIdType = "EXTERNAL_ID",
  locale,
}: GetProductRequest): Promise<GetProductResponse> => {
  try {
    // Parameter validation
    if (!productIdentifier?.trim()) {
      throw new Error("Product identifier is required");
    }

    const { data, error } = await useFetch<GetProductResponse>(
      `/api/product/${productIdentifier}`,
      {
        params: {
          productIdType,
          locale,
        },
        method: "GET",
        // Enable Nuxt caching for performance
        key: `product-${productIdentifier}-${productIdType}-${locale}`,
        // Set cache TTL
        default: () => ({ success: false, product: null }),
      }
    );

    if (error.value) {
      console.error("Failed to fetch product:", {
        productIdentifier,
        productIdType,
        error: error.value,
      });

      return {
        success: false,
        product: null,
      } as GetProductResponse;
    }

    return data.value as GetProductResponse;
  } catch (error) {
    console.error("Unexpected error in getProductbyId:", error);

    return {
      success: false,
      product: null,
    } as GetProductResponse;
  }
};

Execution Flow

Step-by-Step Process

  1. Parameter Validation

    // Validate required parameters
    if (!productIdentifier?.trim()) {
      throw new Error("Product identifier is required");
    }
  2. Authentication Check

    // Nuxt automatically includes authentication headers
    // JWT token from cookies attached to request
    const authToken = useCookie("token").value;
  3. API Request Construction

    // Build request with parameters and defaults
    const requestUrl = `/api/product/${productIdentifier}`;
    const requestParams = {
      productIdType: productIdType || "EXTERNAL_ID",
      locale: locale || useRuntimeConfig().public.locale,
    };
  4. Network Request Execution

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

    // Process response and handle errors
    if (error.value) {
      return handleError(error.value);
    }
    
    return processSuccessResponse(data.value);
  6. Data Transformation

    // Transform response for component consumption
    const processedProduct = {
      ...data.value.product,
      // Additional processing if needed
    };
  7. Return Formatted Response

    // Return structured response
    return {
      success: true,
      product: processedProduct,
    };