Autocomplete
The autoCompleteSearchProducts
function provides real-time search suggestions as users type in search inputs. This function is essential for creating responsive and intuitive search experiences, enabling users to quickly discover products without typing complete product names or navigating through complex category structures.
The autocomplete functionality leverages intelligent search algorithms to provide contextually relevant suggestions based on partial input. It supports multi-language queries, currency-specific results, and optional aggregation data to enhance the suggestion quality. The function is optimized for performance with built-in caching and debouncing capabilities.
This function is particularly valuable in B2B e-commerce scenarios where users often search for specific products by partial SKUs, brand names, or technical specifications, enabling faster product discovery and improved user experience.
Process 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 participant Auth as Auth Service User->>Component: Type Search Query Component->>Component: Debounce Input (300ms) Component->>useSearchProduct: autoCompleteSearchProducts(params) useSearchProduct->>useSearchProduct: Validate Input Length useSearchProduct->>SDK: useFetch('/api/search/autocomplete') SDK->>Auth: Verify Authentication Token Auth-->>SDK: Token Valid SDK->>API: GET /api/search/autocomplete alt Success Response API-->>SDK: 200 - Autocomplete Results SDK-->>useSearchProduct: AutocompleteResponse useSearchProduct->>useSearchProduct: Process Results useSearchProduct-->>Component: Suggestions Array Component-->>User: Display Dropdown Suggestions else No Results Found API-->>SDK: 200 - Empty Results SDK-->>useSearchProduct: Empty Response useSearchProduct-->>Component: Empty Array Component-->>User: "No suggestions found" else Authentication Error Auth-->>SDK: 401 - Unauthorized SDK-->>useSearchProduct: Auth Error useSearchProduct-->>Component: Authentication Error Component-->>User: "Please log in to search" else Server Error API-->>SDK: 500 - Internal Error SDK-->>useSearchProduct: Server Error useSearchProduct->>useSearchProduct: Log Error useSearchProduct-->>Component: Empty Array Component-->>User: "Search temporarily unavailable" end
Call Parameters
The function accepts an AutocompleteProductsRequest
object with the following structure:
AutocompleteProductsRequest Interface (from SDK)
interface AutocompleteProductsRequest {
input: string;
locale?: string;
currency?: string;
pageable?: Pageable;
aggregation?: AggregationType;
productTags?: string[];
}
interface Pageable {
page?: number;
size?: number;
sort?: string[];
}
enum AggregationType {
PRODUCT = "PRODUCT",
VARIANT = "VARIANT",
OFFER = "OFFER",
}
Parameter Details
Parameter | Type | Required | Default | Example | Business Impact |
---|---|---|---|---|---|
input | string | ✅ Yes | - | "laptop" , "DELL" , "i7" | Critical: Search term for autocomplete suggestions |
locale | string | ❌ Optional | Runtime config | "en-GB" , "fr-FR" | Localization: Affects suggestion language and relevance |
currency | string | ❌ Optional | Runtime config | "EUR" , "USD" | Pricing: Currency context for price-aware suggestions |
pageable.page | number | ❌ Optional | 0 | 0 , 1 | Performance: Controls result pagination |
pageable.size | number | ❌ Optional | 20 | 5 , 10 , 20 | Performance: Limits suggestion count |
aggregation | AggregationType | ❌ Optional | PRODUCT | PRODUCT , VARIANT | Data Scope: Determines aggregation level |
productTags | string[] | ❌ Optional | [] | ["electronics", "premium"] | Filtering: Restricts suggestions to tagged products |
Complete Example Call
const autocompleteParams: AutocompleteProductsRequest = {
input: "dell laptop",
locale: "en-GB",
currency: "EUR",
pageable: {
page: 0,
size: 10,
},
aggregation: AggregationType.PRODUCT,
productTags: ["electronics", "business"],
};
const suggestions = await autoCompleteSearchProducts(autocompleteParams);
Returns from Composable
The function returns an array of product suggestions:
AutocompleteResponse Structure
// Return type (inferred from API response)
interface AutocompleteResponse {
success: boolean;
products: ProductSearchContent[];
}
interface ProductSearchContent {
offerPrice: OfferPriceSearch;
offer: OfferSearch;
variant: VariantSearch;
product: ProductSearch;
attributes: AttributeSearch[];
supplier: SupplierSearch;
}
interface ProductSearch {
id: string;
externalId: string;
sku: string;
name: string;
description: string | null;
brand: string | null;
mainPictureUrl: string | null;
tags: any[];
unit: string | null;
}
interface VariantSearch {
id: string;
externalId: string;
sku: string;
name: string;
description: string | null;
pictureUrls: PictureUrl[];
ean: string;
mpn: string | null;
}
Realistic Example JSON Response
[
{
"offerPrice": {
"unitPrice": 899.99,
"currency": "EUR",
"taxIncluded": false
},
"offer": {
"id": "offer-001",
"externalId": "EXT-OFFER-001",
"quantityPerItem": 1,
"stock": 150,
"currency": "EUR",
"minOrderQuantity": 1,
"maxOrderQuantity": 100,
"leadTimeToShip": 2
},
"variant": {
"id": "variant-001",
"externalId": "DELL-LAT-5520-16GB",
"sku": "DELL-LAT-5520-16GB-SLV",
"name": "Dell Latitude 5520 - 16GB RAM - Silver",
"description": "Professional laptop with Intel i7 processor",
"pictureUrls": [
{
"url": "https://cdn.example.com/dell-latitude-5520-main.jpg",
"width": 800,
"height": 600
}
],
"ean": "1234567890123",
"mpn": "LAT5520-16-SLV"
},
"product": {
"id": "product-001",
"externalId": "DELL-LATITUDE-5520",
"sku": "DELL-LAT-5520",
"name": "Dell Latitude 5520",
"description": "Professional business laptop series",
"brand": "Dell",
"mainPictureUrl": "https://cdn.example.com/dell-latitude-main.jpg",
"tags": [
{
"name": "Business",
"category": "USE_CASE"
},
{
"name": "Intel",
"category": "PROCESSOR"
}
],
"unit": "piece"
},
"attributes": [
{
"name": "RAM Size",
"externalId": "RAM_SIZE",
"value": "16GB",
"values": ["16GB"]
},
{
"name": "Color",
"externalId": "COLOR",
"value": "Silver",
"values": ["Silver"]
}
],
"supplier": {
"id": "supplier-001",
"name": "TechPro Distribution",
"externalId": "TECH-PRO-001"
}
},
{
"offerPrice": {
"unitPrice": 1299.99,
"currency": "EUR",
"taxIncluded": false
},
"offer": {
"id": "offer-002",
"externalId": "EXT-OFFER-002",
"quantityPerItem": 1,
"stock": 75,
"currency": "EUR",
"minOrderQuantity": 1,
"maxOrderQuantity": 50,
"leadTimeToShip": 3
},
"variant": {
"id": "variant-002",
"externalId": "DELL-XPS-13-32GB",
"sku": "DELL-XPS-13-32GB-BLK",
"name": "Dell XPS 13 - 32GB RAM - Black",
"description": "Premium ultrabook with enhanced performance",
"pictureUrls": [
{
"url": "https://cdn.example.com/dell-xps-13-main.jpg",
"width": 800,
"height": 600
}
],
"ean": "1234567890124",
"mpn": "XPS13-32-BLK"
},
"product": {
"id": "product-002",
"externalId": "DELL-XPS-13",
"sku": "DELL-XPS-13",
"name": "Dell XPS 13",
"description": "Premium ultrabook series for professionals",
"brand": "Dell",
"mainPictureUrl": "https://cdn.example.com/dell-xps-main.jpg",
"tags": [
{
"name": "Premium",
"category": "TIER"
},
{
"name": "Ultrabook",
"category": "FORM_FACTOR"
}
],
"unit": "piece"
},
"attributes": [
{
"name": "RAM Size",
"externalId": "RAM_SIZE",
"value": "32GB",
"values": ["32GB"]
},
{
"name": "Color",
"externalId": "COLOR",
"value": "Black",
"values": ["Black"]
}
],
"supplier": {
"id": "supplier-002",
"name": "Premium Tech Solutions",
"externalId": "PREM-TECH-001"
}
}
]
Error Management
HTTP Error Codes and Handling
Error Code | Cause | System Action | User Message | Return Format |
---|---|---|---|---|
400 | Invalid input parameters or malformed request | Log validation error, return empty array | "Invalid search parameters" | [] |
401 | Authentication token missing/invalid | Trigger re-authentication flow | "Please log in to search products" | Authentication redirect |
403 | User lacks search permissions | Log access attempt, return empty array | "Search access denied" | [] |
404 | No autocomplete endpoint or service | Log service error, return empty array | "Search service unavailable" | [] |
429 | Rate limit exceeded | Log rate limit hit, return empty array | "Too many search requests, please slow down" | [] |
500 | Internal server error | Log server error, return empty array | "Search temporarily unavailable" | [] |
Error Handling Example Code
// Global error handling in composable
const autoCompleteSearchProducts = async ({
input,
locale,
currency,
pageable,
aggregation,
productTags,
}: AutocompleteProductsRequest) => {
try {
// Input validation
if (!input?.trim() || input.length < 2) {
console.warn("Autocomplete requires at least 2 characters");
return [];
}
// Set loading state
loading.value = true;
const { data, status, error } = await useFetch("/api/search/autocomplete", {
params: {
input,
locale,
currency,
pageable: JSON.stringify(pageable),
aggregation,
productTags: JSON.stringify(productTags),
},
key: `autocomplete-${input}-${locale}-${currency}-${JSON.stringify(
pageable
)}-${aggregation}`,
});
// Update loading state
loading.value = status.value === "pending";
if (error.value) {
console.error("Error fetching autocomplete products:", {
input,
locale,
error: error.value,
});
return [];
}
// Return products array or empty array
return data.value?.products || [];
} catch (error) {
console.error("Unexpected error in autoCompleteSearchProducts:", error);
return [];
} finally {
loading.value = false;
}
};
// Component-level error handling
const handleAutocomplete = async (searchTerm: string) => {
try {
if (searchTerm.length < 2) {
suggestions.value = [];
return;
}
const results = await autoCompleteSearchProducts({
input: searchTerm,
locale: userLocale.value,
currency: userCurrency.value,
pageable: { page: 0, size: 8 },
});
suggestions.value = results;
} catch (error) {
console.error("Autocomplete error:", error);
// User notification for persistent errors
useToast().add({
title: "Search Error",
description: "Unable to load search suggestions",
color: "yellow",
});
// Fallback to empty suggestions
suggestions.value = [];
}
};
Use Cases
1. Real-time Search Suggestions
Provide instant search suggestions as users type in search inputs for improved discovery.
Scenario: User types "dell" in search bar and sees immediate product suggestions.
Parameters: { input: "dell", locale: "en-GB", pageable: { page: 0, size: 8 } }
Expected Outcome: List of Dell products displayed in dropdown with images and prices.
2. SKU-based Quick Search
Enable rapid product lookup using partial SKUs for technical users and repeat buyers.
Scenario: Procurement specialist searches using partial SKU "LAT-552" to find specific laptop models.
Parameters: { input: "LAT-552", currency: "EUR", aggregation: "VARIANT" }
Expected Outcome: Specific Dell Latitude 5520 variants displayed with precise model information.
3. Brand and Category Filtering
Provide filtered autocomplete suggestions within specific product categories or brands.
Scenario: User searches "intel" within electronics category for processor-based filtering.
Parameters: { input: "intel", productTags: ["electronics"], pageable: { size: 12 } }
Expected Outcome: Intel-powered devices shown with processor specifications highlighted.
4. Multi-language Product Discovery
Support international users with localized product names and descriptions in autocomplete.
Scenario: French user searches "ordinateur portable" for laptop suggestions in French.
Parameters: { input: "ordinateur portable", locale: "fr-FR", currency: "EUR" }
Expected Outcome: Laptop suggestions with French product names and descriptions.
Important Points
Performance Considerations
- Debouncing Strategy: Implement 300ms debounce to prevent excessive API calls during rapid typing
- Intelligent Caching: Autocomplete responses cached with unique keys including all parameters
- Result Limiting: Keep suggestion count between 5-10 items for optimal user experience
- Progressive Enhancement: Graceful degradation when autocomplete fails or is unavailable
Security Aspects
- Input Validation: Server-side validation prevents injection attacks through search terms
- Authentication Integration: All requests include JWT tokens for user-specific results
- Rate Limiting: API endpoints protected against abuse with configurable rate limits
- Data Filtering: Results filtered based on user permissions and accessible product catalogs
Flexibility Features
- Multi-language Support: Autocomplete adapts to user's locale for relevant suggestions
- Currency Awareness: Pricing information displayed in user's preferred currency
- Aggregation Levels: Support for product, variant, or offer-level suggestions
- Tag-based Filtering: Ability to scope suggestions to specific product categories or tags
Integration Capabilities
- Search Enhancement: Seamless integration with full product search functionality
- Analytics Integration: Track autocomplete usage patterns and popular search terms
- Cart Integration: Direct "add to cart" capability from autocomplete suggestions
- Navigation Support: Smart routing to product detail pages from suggestion selection
Technical Implementation
Composable Function with Complete JSDoc
/**
* Provides real-time autocomplete suggestions for product search
*
* @param params - Autocomplete request parameters
* @param params.input - Search term for generating suggestions
* @param params.locale - Locale for internationalized suggestions
* @param params.currency - Currency for pricing context
* @param params.pageable - Pagination configuration
* @param params.aggregation - Aggregation level for results
* @param params.productTags - Tags to filter suggestions
* @returns Promise resolving to array of product suggestions
*
* @example
* ```typescript
* const { autoCompleteSearchProducts } = useSearchProduct();
*
* const suggestions = await autoCompleteSearchProducts({
* input: "dell laptop",
* locale: "en-GB",
* currency: "EUR",
* pageable: { page: 0, size: 8 }
* });
*
* console.log('Suggestions found:', suggestions.length);
* suggestions.forEach(product => {
* console.log(`${product.product.name}: €${product.offerPrice.unitPrice}`);
* });
* ```
*
* @throws {Error} When network request fails or invalid input provided
* @since 1.0.0
*/
const autoCompleteSearchProducts = async ({
input,
locale,
currency,
pageable,
aggregation,
productTags,
}: AutocompleteProductsRequest) => {
try {
// Input validation
if (!input?.trim()) {
console.warn("Autocomplete input is required");
return [];
}
if (input.length < 2) {
console.info("Autocomplete requires at least 2 characters");
return [];
}
// Set loading state
loading.value = true;
const { data, status, error } = await useFetch("/api/search/autocomplete", {
params: {
input: input.trim(),
locale,
currency,
pageable: JSON.stringify(pageable),
aggregation,
productTags: JSON.stringify(productTags),
},
// Unique cache key for this specific search
key: `autocomplete-${input}-${locale}-${currency}-${JSON.stringify(
pageable
)}-${aggregation}`,
});
// Sync loading state with request status
loading.value = status.value === "pending";
// Handle API errors
if (error.value) {
console.error("Error fetching autocomplete products:", {
input,
locale,
currency,
error: error.value,
});
return [];
}
// Return products array or empty fallback
return data.value?.products || [];
} catch (error) {
console.error("Unexpected error in autoCompleteSearchProducts:", error);
return [];
} finally {
// Ensure loading state is always reset
loading.value = false;
}
};
Execution Flow
Step-by-Step Process
-
Input Validation
// Validate search input requirements if (!input?.trim() || input.length < 2) { console.warn("Autocomplete requires at least 2 characters"); return []; }
-
Loading State Management
// Set loading indicator for UI feedback loading.value = true;
-
Parameter Preparation
// Prepare request parameters with defaults const requestParams = { input: input.trim(), locale: locale || useRuntimeConfig().public.locale, currency: currency || useRuntimeConfig().public.currency, pageable: JSON.stringify(pageable || { page: 0, size: 20 }), aggregation: aggregation || "PRODUCT", productTags: JSON.stringify(productTags || []), };
-
Cache Key Generation
// Generate unique cache key for this search const cacheKey = `autocomplete-${input}-${locale}-${currency}-${JSON.stringify( pageable )}-${aggregation}`;
-
API Request Execution
// Execute autocomplete search request const { data, status, error } = await useFetch("/api/search/autocomplete", { params: requestParams, key: cacheKey, });
-
Response Processing
// Handle successful response or errors if (error.value) { logError("Autocomplete failed", { input, error: error.value }); return []; }
-
Result Formatting
// Return formatted suggestions array return data.value?.products || [];
-
State Cleanup
// Reset loading state loading.value = false;
Updated about 2 months ago