Search

This documentation provides a comprehensive overview of the Search management system within the Nuxt 3 e-commerce B2B application. The system consists of the main composable useSearchProduct that handles product searching, autocomplete functionality, and advanced filtering capabilities.

System Architecture

The Search system is built around the useSearchProduct composable that provides comprehensive search functionality for products, suppliers, and attributes:

graph TB
    subgraph "Search Management Architecture"
        User[User Interface]

        subgraph "Composables Layer"
            USP[useSearchProduct]
        end

        subgraph "useSearchProduct Structure"
            USPA[useSearchProductApi]
            USPG[useSearchProductGetters]
            USPH[useSearchProductHelper]
        end

        subgraph "Backend Integration"
            SDK[Djust SDK]
            API[API Routes]
        end

        subgraph "Search Features"
            AUTO[Autocomplete Search]
            FULL[Full Product Search]
            FILTER[Advanced Filtering]
            FACET[Faceted Navigation]
        end
    end

    User --> USP

    USP --> USPA
    USP --> USPG
    USP --> USPH

    USPA --> SDK
    SDK --> API

    USPA --> AUTO
    USPA --> FULL
    USPA --> FILTER
    USPA --> FACET

    style USP fill:#e1f5fe
    style SDK fill:#e8f5e8
    style AUTO fill:#fff3e0
    style FULL fill:#f3e5f5

Data Structure Overview

The Search system manages several key data types for comprehensive product discovery:

EntityDescriptionKey PropertiesSource
ProductSearchContentMain search result itemproduct, variant, offer, attributesSDK SearchProduct
ProductSearchBasic product informationid, sku, name, brand, descriptionSDK ProductSearch
VariantSearchProduct variant detailssku, name, pictureUrls, ean, mpnSDK VariantSearch
OfferSearchPricing and availabilitystock, currency, minOrderQuantity, maxOrderQuantitySDK OfferSearch
OfferPriceSearchDetailed pricing infounitPrice, currency, taxIncludedSDK OfferPriceSearch
AttributeSearchProduct attributesname, externalId, value, valuesSDK AttributeSearch
SupplierSearchSupplier informationid, name, externalIdSDK SupplierSearch
FacetsSearch refinement optionsattributes, suppliers, brands, productTagsCustom Facets

Core Functionality

Search Operations Flow

sequenceDiagram
    participant User as User
    participant Component as Vue Component
    participant useSearchProduct as useSearchProduct
    participant SDK as Djust SDK
    participant API as API Server

    User->>Component: Enter Search Query
    Component->>useSearchProduct: autoCompleteSearchProducts(params)
    useSearchProduct->>SDK: useFetch('/api/search/autocomplete')
    SDK->>API: GET /api/search/autocomplete
    API-->>SDK: Autocomplete Results
    SDK-->>useSearchProduct: AutocompleteResponse
    useSearchProduct-->>Component: Suggestions List
    Component-->>User: Display Suggestions

    User->>Component: Select/Refine Search
    Component->>useSearchProduct: getProductsList(params)
    useSearchProduct->>SDK: useFetch('/api/search/products')
    SDK->>API: GET /api/search/products
    API-->>SDK: Search Results + Facets
    SDK-->>useSearchProduct: SearchProductsResponse
    useSearchProduct-->>Component: Products + Filters
    Component-->>User: Display Results

    Note over useSearchProduct,SDK: Caching enabled for performance
    Note over API: Authentication & filtering applied

Advanced Filtering Flow

sequenceDiagram
    participant User as User
    participant Component as Vue Component
    participant useSearchProduct as useSearchProduct
    participant Helpers as SearchProductHelper

    User->>Component: Apply Filters
    Component->>useSearchProduct: getProductsList(filters)
    useSearchProduct->>useSearchProduct: Process Search Request
    useSearchProduct-->>Component: Filtered Results

    Component->>Helpers: getFacets(searchResponse)
    Helpers->>Helpers: Process Facet Data
    Helpers-->>Component: Available Filters

    Component->>Helpers: getAttributeValueByName(product, name)
    Helpers->>Helpers: Extract Attribute Value
    Helpers-->>Component: Specific Attribute

    Component-->>User: Update UI with Results & Filters

Permission-Based Access Control

Public vs Authenticated Data Access

The search system provides different levels of data access based on authentication status:

API FunctionUnauthenticated AccessAuthenticated Access
autoCompleteSearchProductsAll products with public offers onlyAll products with all available offers
getProductsListAll products with public offers in best offersAll products with complete offer data including exclusive pricing

Main Features

1. Autocomplete Search

The system provides real-time search suggestions as users type:

  • Intelligent Suggestions: Context-aware product suggestions based on partial input
  • Multi-language Support: Autocomplete adapts to user's locale settings
  • Performance Optimized: Debounced requests with intelligent caching
  • Aggregation Support: Optional aggregation data for enhanced suggestions

2. Full Product Search

Comprehensive product search with advanced filtering capabilities:

  • Text Search: Full-text search across product names, descriptions, and SKUs
  • Faceted Navigation: Filter by brands, suppliers, attributes, and product tags
  • Pagination Support: Efficient handling of large result sets
  • Sort Options: Multiple sorting criteria (name, price, relevance)

3. Advanced Filtering

Sophisticated filtering system for precise product discovery:

  • Attribute Filtering: Filter by specific product attributes and values
  • Supplier Filtering: Restrict results to specific suppliers
  • Brand Filtering: Focus on particular brands or manufacturers
  • Custom Field Filtering: Support for custom business-specific filters

4. Data Extraction and Processing

Comprehensive getter functions for extracting specific data from search results:

  • Product Information: Extract names, descriptions, SKUs, and brands
  • Pricing Data: Access unit prices, quantities, and stock information
  • Variant Details: Retrieve variant-specific information and images
  • Attribute Processing: Extract and process product attributes by name or ID

Key Points

Performance Considerations

  • Intelligent Caching: Search requests are cached with unique keys to reduce API calls
  • Debounced Autocomplete: Prevents excessive API requests during typing
  • Pagination Strategy: Large result sets are efficiently paginated for optimal load times
  • Facet Optimization: Facets are loaded conditionally to improve performance

Security & Authentication

  • JWT Integration: All search requests include authentication headers
  • Permission Filtering: Backend filters results based on user permissions and access rights
  • Data Privacy: Sensitive pricing and supplier information filtered by user role
  • Rate Limiting: API calls are rate-limited to prevent abuse

Flexibility & Configuration

  • Multi-locale Support: Search adapts to user's language and regional preferences
  • Currency Handling: Pricing data displayed in user's preferred currency
  • Configurable Filters: Flexible filter system supports custom business rules
  • Extensible Attributes: Supports new product attributes without code changes

Integration Capabilities

  • SDK Abstraction: Clean separation between UI logic and search API communication
  • Type Safety: Full TypeScript support with SDK-generated interfaces
  • Composable Architecture: Modular structure allows selective search feature usage
  • Error Propagation: Consistent error handling across all search operations

Best Practices

Search Implementation

When implementing search functionality, follow these recommended patterns:

// ✅ Correct: Use debounced autocomplete for better UX
const searchQuery = ref("");
const searchResults = ref([]);

const debouncedSearch = useDebounceFn(async (query: string) => {
  if (query.length >= 2) {
    const { autoCompleteSearchProducts } = useSearchProduct();
    const results = await autoCompleteSearchProducts({
      input: query,
      locale: userLocale.value,
      currency: userCurrency.value,
      pageable: { page: 0, size: 10 },
    });
    searchResults.value = results;
  }
}, 300);

watch(searchQuery, (newQuery) => {
  debouncedSearch(newQuery);
});

Filter Management

Implement efficient filter management for complex searches:

// ✅ Correct: Structured filter management
const searchFilters = ref({
  currency: "EUR",
  locale: "en-GB",
  brand: [],
  attributes: [],
  productTags: [],
  suppliers: [],
});

const applyFilters = async () => {
  const { getProductsList } = useSearchProduct();

  const searchParams = {
    locale: searchFilters.value.locale,
    filters: searchFilters.value,
    pageable: { page: 0, size: 20 },
    includeFacets: true,
  };

  const results = await getProductsList(searchParams);
  return results;
};

Error Handling

Implement robust error handling for search operations:

// ✅ Correct: Comprehensive search error handling
const performSearch = async (searchTerm: string) => {
  try {
    isLoading.value = true;

    const { getProductsList } = useSearchProduct();
    const response = await getProductsList({
      locale: userLocale.value,
      filters: {
        ...currentFilters.value,
        query: searchTerm,
      },
      includeFacets: true,
    });

    if (response.success) {
      searchResults.value = response.products;
      availableFacets.value = response.facets;
    } else {
      throw new Error("Search request failed");
    }
  } catch (error) {
    console.error("Search error:", error);

    useToast().add({
      title: "Search Error",
      description: "Unable to perform search. Please try again.",
      color: "red",
    });

    // Fallback to empty results
    searchResults.value = [];
  } finally {
    isLoading.value = false;
  }
};

Detailed Documentation

This overview provides the foundation for understanding the Search management system. For detailed implementation guides, API specifications, and advanced usage patterns, refer to the following specialized documentation:

Function Documentation

System Documentation

The Search system serves as the primary product discovery mechanism for the e-commerce platform, providing users with powerful, flexible, and performant search capabilities across the entire product catalog.