### A/B Testing Setup Source: https://github.com/blazity/enterprise-commerce/blob/main/README.md Demonstrates the setup for A/B testing within the application's middleware. This configuration allows for easy implementation of A/B tests. ```typescript import { NextRequest, NextResponse } from "next/server"; export const middleware = async (request: NextRequest) => { const url = request.nextUrl.clone(); if (url.pathname.match(/^(?!.*\.)[^/]+/u)) { const response = NextResponse.next(); response.cookies.set( "ab-test", Math.random() > 0.5 ? "A" : "B" ); return response; } return NextResponse.next(); }; ``` -------------------------------- ### Environment Setup Variables Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/README.md Essential environment variables for configuring the Shopify and Algolia integrations. Refer to configuration.md for a complete list. ```bash SHOPIFY_STORE_DOMAIN=mystore.myshopify.com SHOPIFY_STOREFRONT_ACCESS_TOKEN=your-token ALGOLIA_APPLICATION_ID=your-app-id ALGOLIA_API_KEY=your-search-key # ... (see configuration.md for complete list) ``` -------------------------------- ### GET /api/reviews/ai-summary Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/endpoints.md Generates AI summaries of product reviews using OpenAI GPT-4o. Requires authentication. ```APIDOC ## GET /api/reviews/ai-summary ### Description Generate AI summaries of product reviews using OpenAI GPT-4o. ### Method GET ### Endpoint /api/reviews/ai-summary ### Authentication Required ### Headers - **Authorization** (string) - Required - Bearer token (format: `Bearer `) ### Response #### Success Response (200) - **message** (string) - Status message indicating generation completion. #### Error Response (401) - Description: Unauthorized - invalid or missing authorization. #### Error Response (500) - Description: Feature not opted in, demo mode, or missing reviews index. #### Response Example { "message": "Reviews synced" } ### Max Duration 60 seconds ### Dependencies OpenAI API key (GPT-4o model) ``` -------------------------------- ### Get Single Mock Product by Handle for Demo Mode Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/utilities.md Retrieves a single mock product by its handle, used in demo mode. ```typescript getDemoSingleProduct(handle: string): CommerceProduct | null ``` -------------------------------- ### GET /api/reviews/sync Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/endpoints.md Synchronizes product reviews from Judge.me to the Algolia index. Requires authentication. ```APIDOC ## GET /api/reviews/sync ### Description Synchronize product reviews from Judge.me to Algolia index. ### Method GET ### Endpoint /api/reviews/sync ### Authentication Required ### Headers - **Authorization** (string) - Required - Bearer token (format: `Bearer `) ### Response #### Success Response (200) - **message** (string) - Status message indicating sync completion. #### Error Response (401) - Description: Unauthorized - invalid or missing authorization token. #### Error Response (500) - Description: Review feature not opted in, demo mode, or missing Algolia reviews index. #### Response Example { "message": "All synced" } ### Rate Limiting Vercel Firewall `algolia-data-sync` key ### Max Duration 60 seconds ``` -------------------------------- ### Review Management Functions Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/README.md Examples for fetching product reviews and submitting a new review using the `lib/reviews` module. Review submission is handled as a server action. ```typescript import { getProductReviews, submitReview } from 'lib/reviews' // Get reviews for product const { reviews, total } = await getProductReviews('product-handle', { page: 0, limit: 10 }) // Submit review (server action) await submitReview({ name: 'User', email: 'user@example.com', rating: 5, body: 'Great product!', id: 'product-id' }) ``` -------------------------------- ### Example Shopify Webhook Payload Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/endpoints.md This is an example of the JSON payload received from Shopify for product or collection webhooks. ```json { "id": 7208243470496, "title": "Blue Cotton Shirt", "handle": "blue-cotton-shirt" } ``` -------------------------------- ### Example .env.local File Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/configuration.md A sample `.env.local` file demonstrating required environment variables for Shopify, Algolia, and optional services like Judge.me and OpenAI. Includes feature flags and authentication secrets. ```bash # Shopify SHOPIFY_STORE_DOMAIN=mystore.myshopify.com SHOPIFY_STOREFRONT_ACCESS_TOKEN=your-token SHOPIFY_ADMIN_ACCESS_TOKEN=shpat_your-token SHOPIFY_APP_API_SECRET_KEY=your-webhook-secret SHOPIFY_HIERARCHICAL_NAV_HANDLE=main-menu # Algolia ALGOLIA_APPLICATION_ID=YOUR_APP_ID ALGOLIA_API_KEY=your-search-key ALGOLIA_PRODUCTS_INDEX=products ALGOLIA_CATEGORIES_INDEX=categories ALGOLIA_REVIEWS_INDEX=reviews # Judge.me (optional) JUDGE_BASE_URL=https://api.judge.me/v1 JUDGE_API_TOKEN=your-judge-token # OpenAI (optional) OPENAI_API_KEY=sk-your-api-key # Authentication CRON_SECRET=your-strong-random-secret-token # Features DEMO_MODE=false NODE_ENV=production ``` -------------------------------- ### Example Webhook Success Response Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/endpoints.md This is the expected JSON response when a webhook is processed successfully. ```json { "message": "Success" } ``` -------------------------------- ### Get Mock Product Data for Demo Mode Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/utilities.md Retrieves mock product data, typically used when the application is running in demo mode. ```typescript getDemoProducts(): { hits: CommerceProduct[] } ``` -------------------------------- ### Get All Product Reviews Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/reviews.md Fetches all product reviews with a 24-hour revalidation cache. Use this to retrieve a list of reviews for a product. ```typescript export const getAllProductReviews: () => Promise ``` ```typescript import { getAllProductReviews } from 'lib/reviews' const reviews = await getAllProductReviews() ``` -------------------------------- ### Get Similar Products using AI Recommendations Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/algolia.md Find products similar to a given product based on AI recommendations. Useful for 'you might also like' sections. ```typescript import { getSimilarProducts } from 'lib/algolia' const similar = await getSimilarProducts('clothing', 'product-123') console.log(similar) // Up to 8 similar products ``` -------------------------------- ### Get Demo Navigation Items Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/utilities.md Retrieves navigation items specifically for demo mode. Source located in utils/nav-items.ts. ```typescript navItems(): NavigationItem[] ``` -------------------------------- ### Get a Single Product by Handle Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/algolia.md Retrieve a specific product using its unique handle. Useful for displaying individual product details. ```typescript import { getProduct } from 'lib/algolia' const product = await getProduct('my-awesome-product') if (product) { console.log(product.title, product.minPrice) } ``` -------------------------------- ### navItems Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/utilities.md Get navigation items for demo mode. This utility function retrieves navigation data specifically for the demo environment. ```APIDOC ## navItems ### Description Get navigation items for demo mode. This function is used to retrieve navigation data when the application is running in demo mode. ### Method ```typescript navItems(): NavigationItem[] ``` ### Response - **NavigationItem[]** - An array of navigation items. ### Example ```typescript // Assuming NavigationItem is defined elsewhere const navigation = navItems(); ``` ``` -------------------------------- ### Algolia Client Usage Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/README.md Examples of using the Algolia client to fetch single products and perform filtered searches. Ensure the Algolia client is properly configured. ```typescript import { getProduct, getFilteredProducts } from 'lib/algolia' // Get single product const product = await getProduct('product-handle') // Search with filters const results = await getFilteredProducts( 'blue shirt', 'price:asc', 1, 'vendor:"Nike" AND minPrice >= 50' ) ``` -------------------------------- ### Get All Product Reviews Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/reviews.md Retrieve all reviews for a product, automatically handling pagination. Use this when you need to process all reviews without managing page requests manually. ```typescript const allReviews = await client.getAllProductReviews() console.log(`Total reviews: ${allReviews.length}`) ``` -------------------------------- ### Get Page Display Type Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/utilities.md Determines the rendering strategy for a given pathname. Useful for managing caching and rendering logic. ```typescript getPageDisplayType(pathname: string): 'ppp' | 'isr' | 'ssr' | 'csr' ``` ```typescript import { getPageDisplayType } from 'utils/get-page-display-type' const type = getPageDisplayType('/product/my-product') // Helps determine caching and rendering strategy ``` -------------------------------- ### getProductReviews Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/reviews.md Get reviews for a specific product with pagination. Allows specifying the number of reviews per page and the page number. ```APIDOC ## getProductReviews ### Description Get reviews for a specific product with pagination. ### Method Client Method ### Parameters #### Path Parameters None #### Query Parameters - **opts.per_page** (number) - No - 10 - Number of reviews per page - **opts.page** (number) - No - 1 - Page number (1-indexed) #### Request Body None ### Request Example ```typescript const response = await client.getProductReviews({ per_page: 15, page: 2 }) ``` ### Response #### Success Response - **current_page** (number) - Current page number - **per_page** (number) - Number of reviews per page - **total** (number) - Total number of reviews - **totalPages** (number) - Total number of pages - **reviews** (Review[]) - Array of Review objects #### Response Example ```json { "current_page": 1, "per_page": 10, "total": 50, "totalPages": 5, "reviews": [ { "id": "review_id_1", "rating": 5, "body": "Great product!", "name": "John Doe", "email": "john@example.com" } ] } ``` ### Source `lib/reviews/client.ts:31-56` ``` -------------------------------- ### Get Mock Review Data for Demo Mode Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/utilities.md Retrieves mock review data, typically used when the application is running in demo mode. ```typescript getDemoProductReviews(): { reviews: Review[]; total: number } ``` -------------------------------- ### GET /api/navigation Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/endpoints.md Retrieves the application's navigation structure, including menu items. This endpoint is cacheable for improved performance. ```APIDOC ## GET /api/navigation ### Description Retrieve application navigation items/menu structure. ### Method GET ### Endpoint /api/navigation ### Response #### Success Response (200) - **items** (NavigationItem[]) - Array of navigation menu items. #### Response Example { "items": [] } ### Cache 360 seconds ``` -------------------------------- ### Webhook Configuration for Shopify Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/README.md Specifies the endpoint URL and the topics for which Shopify webhooks should be configured. This setup ensures that the application receives real-time updates on product and collection changes. ```shell https:///api/feed/sync Topics: products/create, products/update, products/delete, collections/create, collections/update, collections/delete ``` -------------------------------- ### Get Featured Products Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/algolia.md Retrieve a curated list of up to 10 featured products. Useful for highlighting specific items on a homepage or promotional section. ```typescript import { getFeaturedProducts } from 'lib/algolia' const featured = await getFeaturedProducts() console.log(featured.length) // Up to 10 featured products ``` -------------------------------- ### Get Shopify Product by Handle Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/shopify.md Retrieve a product using its handle (URL-friendly identifier). Useful for fetching products directly from URLs. Returns a normalized product object or null. ```typescript const product = await client.getProductByHandle('blue-cotton-shirt') console.log(product?.variants) // All available variants ``` -------------------------------- ### Get Shopify Product by GraphQL ID Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/shopify.md Retrieve a product using its unique Shopify GraphQL ID. Returns a normalized product object or null if not found. ```typescript const product = await client.getProduct('gid://shopify/Product/123456789') if (product) { console.log(product.title, product.handle, product.minPrice) } ``` -------------------------------- ### Get Shopify Collection by Handle Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/shopify.md Retrieve a collection using its handle. Returns a collection object with details like title and description, or null if not found. ```typescript const collection = await client.getCollection('summer-sale') if (collection) { console.log(collection.title, collection.descriptionHtml) } ``` -------------------------------- ### ProductCarousel Component using useResponsiveCarousel Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/hooks.md An example of a `ProductCarousel` component that utilizes the `useResponsiveCarousel` hook to manage its behavior based on the current viewport. It demonstrates how to apply custom configurations and use the hook's return values for rendering and navigation. ```typescript 'use client' import { useResponsiveCarousel } from 'hooks/use-responsive-carousel' import { useState } from 'react' export function ProductCarousel({ products }) { const { viewport, config, isMobile, isTablet, isDesktop } = useResponsiveCarousel({ mobile: { slidesToScroll: 1, quality: 60, sizes: "100vw" }, tablet: { slidesToScroll: 2, quality: 75, sizes: "50vw" }, desktop: { slidesToScroll: 3, quality: 90, sizes: "33vw" } }) const [index, setIndex] = useState(0) const handleNext = () => { setIndex(prev => (prev + config.slidesToScroll) % products.length ) } const handlePrev = () => { setIndex(prev => (prev - config.slidesToScroll + products.length) % products.length ) } return (
{products.slice(index, index + config.slidesToScroll).map(product => ( {product.image.altText} ))}
{isMobile && '📱 Mobile'} {isTablet && '📱 Tablet'} {isDesktop && '🖥️ Desktop'}
) } ``` -------------------------------- ### Get or Create Cart Server Action Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/server-actions.md Call this server action to retrieve an existing cart or create a new one. The cart ID is automatically stored in cookies for persistence. ```typescript 'use client' import { getOrCreateCart } from 'app/actions/cart.actions' const { cartId, cart } = await getOrCreateCart() console.log(`Cart ID: ${cartId}`) console.log(`Items in cart: ${cart?.totalQuantity}`) ``` -------------------------------- ### Get Paginated Product Reviews Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/reviews.md Fetch reviews for a specific product, with options to control the number of reviews per page and the page number. Useful for displaying reviews in a paginated interface. ```typescript const response = await client.getProductReviews({ per_page: 15, page: 2 }) console.log(`Page ${response.current_page} of ${response.totalPages}`) console.log(response.reviews) // Array of Review objects ``` -------------------------------- ### Initialize Shopify Client Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/configuration.md Initializes the Shopify client using store domain and access tokens. Ensure SHOPIFY_STORE_DOMAIN, SHOPIFY_STOREFRONT_ACCESS_TOKEN, and SHOPIFY_ADMIN_ACCESS_TOKEN environment variables are set. ```typescript const client = createShopifyClient({ storeDomain: env.SHOPIFY_STORE_DOMAIN, storefrontAccessToken: env.SHOPIFY_STOREFRONT_ACCESS_TOKEN, adminAccessToken: env.SHOPIFY_ADMIN_ACCESS_TOKEN, }) ``` -------------------------------- ### mapCurrencyToSign Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/utilities.md Converts an ISO 4217 currency code into its corresponding currency symbol. For example, 'USD' maps to '$'. ```APIDOC ## mapCurrencyToSign ### Description Convert currency code to symbol. ### Signature ```typescript mapCurrencyToSign(currencyCode: string): string ``` ### Parameters #### Path Parameters - **currencyCode** (string) - Required - ISO 4217 currency code ### Returns Currency symbol (e.g., "$", "€", "£") ### Example ```typescript import { mapCurrencyToSign } from 'utils/map-currency-to-sign' mapCurrencyToSign('USD') // "$" mapCurrencyToSign('EUR') // "€" mapCurrencyToSign('GBP') // "£" ``` ``` -------------------------------- ### getHierarchicalCollections Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/shopify.md Get collections in a hierarchical menu structure, allowing for a specified menu handle and nesting depth. ```APIDOC ## getHierarchicalCollections ### Description Get collections in a hierarchical menu structure. ### Method GET (assumed based on naming convention) ### Endpoint /collections/hierarchy ### Parameters #### Query Parameters - **handle** (string) - Required - Menu handle (e.g., 'main-menu') - **depth** (number) - Optional - Menu nesting depth (default: 3) ### Response #### Success Response (200) - **{ items: MenuItem[] }** - Menu items with nested structure. ### Example ```typescript const menu = await client.getHierarchicalCollections('main-menu', 4) console.log(menu.items) // Nested menu structure ``` ``` -------------------------------- ### Initialize Judge.me Client Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/configuration.md Initializes the Judge.me client with base URL, API token, and shop domain. Ensure JUDGE_BASE_URL, JUDGE_API_TOKEN, and SHOPIFY_STORE_DOMAIN environment variables are configured. ```typescript const reviewsClient = createJudgeClient({ baseUrl: env.JUDGE_BASE_URL, apiKey: env.JUDGE_API_TOKEN, shopDomain: env.SHOPIFY_STORE_DOMAIN, }) ``` -------------------------------- ### Use Pre-instantiated Reviews Client Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/reviews.md Access the globally available `reviewsClient` singleton for convenience. This client is initialized only if the reviews feature is enabled. ```typescript import { reviewsClient } from 'lib/reviews/client' const reviews = await reviewsClient.getProductReviews() ``` -------------------------------- ### Fetch Product with Rate Limiting Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/algolia.md Demonstrates how to use the rate-limited version of `getProduct` to automatically handle Vercel Firewall rate limits. This function will redirect to /429 if rate limits are exceeded. ```typescript import { getProduct } from 'lib/algolia/rate-limited' // This will check rate limits and redirect to /429 if exceeded const product = await getProduct('my-product') ``` -------------------------------- ### Get Category Navigation Items Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/utilities.md Maps demo categories to navigation items. This function is part of the demo utilities. ```typescript categoryItems(): CategoryItem[] ``` -------------------------------- ### ProductEnrichmentBuilder.withAltTags Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/utilities.md Generate AI alt text for product images. ```APIDOC ## withAltTags ### Description Generate AI alt text for product images. ### Returns `Promise` (for chaining) ### Requires - Replicate AI API credentials - `isOptIn('altTags')` to be true ### Example ```typescript const enriched = await new ProductEnrichmentBuilder(product) .withAltTags() .build() console.log(enriched.images[0].altText) // AI-generated description ``` ``` -------------------------------- ### Create Product Review Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/reviews.md A server action wrapper for creating a product review. It takes a payload containing review details and product information. ```typescript export const createProductReview: (payload: ProductReviewBody) => Promise ``` ```typescript import { createProductReview } from 'lib/reviews' const review = await createProductReview({ name: 'Alice', email: 'alice@example.com', rating: 4, body: 'Very good product!', id: 'product-123', ip_addr: '10.0.0.1' }) ``` -------------------------------- ### Generate AI Review Summaries Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/endpoints.md Generates AI summaries for product reviews using OpenAI GPT-4o. Requires an 'Authorization' header. Handles cases with no new reviews or feature opt-in issues. ```bash curl -H "Authorization: Bearer my-secret-token" \ https://example.com/api/reviews/ai-summary # Response: { "message": "Reviews synced" } ``` -------------------------------- ### Create Shopify Client Instance Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/shopify.md Use this factory function to create a Shopify client. Provide your store domain and API access tokens for Storefront and Admin access. ```typescript import { createShopifyClient } from 'lib/shopify/client' const client = createShopifyClient({ storeDomain: 'mystore.myshopify.com', storefrontAccessToken: 'abcd1234...', adminAccessToken: 'shpat_xyz...' }) const product = await client.getProduct('Z2lkOi8vU2hvcGlmeS9Qcm9kdWN0LzEuanNvbg==') ``` -------------------------------- ### Initialize Algolia Client Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/configuration.md Initializes the Algolia client using application ID and API key. Requires ALGOLIA_APPLICATION_ID and ALGOLIA_API_KEY environment variables. ```typescript const algolia = algolia({ applicationId: env.ALGOLIA_APPLICATION_ID, apiKey: env.ALGOLIA_API_KEY, }) ``` -------------------------------- ### Get the most recent product feed Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/shopify.md Retrieves information about the latest product feed. Returns a promise with the feed's ID and status. ```typescript getLatestProductFeed(): Promise ``` ```typescript const latestFeed = await client.getLatestProductFeed() console.log(latestFeed.id, latestFeed.status) ``` -------------------------------- ### Subscribe to Review Webhooks Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/reviews.md Set up a webhook to receive real-time notifications for review events like creation or updates. Provide the event key and the URL to your callback endpoint. ```typescript const webhook = await client.createWebhook( 'review/created', 'https://example.com/api/reviews/sync' ) ``` -------------------------------- ### Get User by Access Token Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/shopify.md Retrieves customer information using their access token. Returns the user object or null if not found. ```typescript const user = await client.getUser('customer-token-xyz') console.log(user?.email, user?.firstName) ``` -------------------------------- ### Get All Shopify Products Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/shopify.md Retrieve an array containing all products available in the store. Useful for displaying a catalog or performing bulk operations. ```typescript const allProducts = await client.getAllProducts() console.log(`Total products: ${allProducts.length}`) ``` -------------------------------- ### getAllProducts Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/shopify.md Retrieve all products from the store. Returns an array of all products. ```APIDOC ## getAllProducts ### Description Retrieve all products from the store. Returns an array of all products. ### Method `getAllProducts(): Promise` ### Returns `Promise` — Array of all products. ### Example ```typescript const allProducts = await client.getAllProducts() console.log(`Total products: ${allProducts.length}`) ``` ``` -------------------------------- ### Get Newest Products Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/algolia.md Retrieve the most recently updated products, up to 8 items. Useful for displaying newly added or modified content. ```typescript import { getNewestProducts } from 'lib/algolia' const newest = await getNewestProducts() console.log(newest) // 8 most recently updated products ``` -------------------------------- ### Create User Account Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/shopify.md Creates a new customer account with provided details. Requires a PlatformUserCreateInput object containing email, password, first name, and last name. ```typescript const user = await client.createUser({ email: 'john@example.com', password: 'secure123!', firstName: 'John', lastName: 'Doe' }) console.log(user.id) ``` -------------------------------- ### Create a new product feed Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/shopify.md Initiates a new product feed for bulk data export. Returns a promise that resolves with the feed ID. ```typescript createProductFeed(): Promise ``` ```typescript const feed = await client.createProductFeed() console.log(feed.id) // Feed ID for polling status ``` -------------------------------- ### GET /api/redirects Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/endpoints.md Looks up redirect rules efficiently using Bloom filters. It helps in redirecting old URLs to new ones. ```APIDOC ## GET /api/redirects ### Description Look up redirect rules using Bloom filters for efficient checking against thousands of redirects. ### Method GET ### Endpoint /api/redirects ### Parameters #### Query Parameters - **pathname** (string) - Required - The path to check for redirects ### Response #### Success Response (200) - **destination** (string) - Target URL for the redirect - **permanent** (boolean) - Whether this is a permanent (301) vs temporary (302) redirect #### Error Response (400) - Description: Missing pathname parameter or no redirect found. #### Response Example { "destination": "/new-product", "permanent": true } ``` -------------------------------- ### createCart Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/shopify.md Create an empty shopping cart, with an option to initialize it with specific items. ```APIDOC ## createCart ### Description Create an empty shopping cart. ### Method POST (assumed based on naming convention) ### Endpoint /carts ### Parameters #### Request Body - **items** (PlatformItemInput[]) - Optional - Initial items to add to cart (default: []) ### Response #### Success Response (200) - **PlatformCart** - New cart object with ID and checkout URL. ### Example ```typescript const cart = await client.createCart([]) console.log(cart.id) // Cart ID for future operations console.log(cart.checkoutUrl) // URL to complete purchase ``` ``` -------------------------------- ### reviewsClient Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/reviews.md Pre-instantiated, opt-in controlled Judge.me client. This is a singleton that checks for feature opt-in before initialization. ```APIDOC ## reviewsClient ### Description Pre-instantiated, opt-in controlled Judge.me client. ### Method Singleton Export ### Parameters None ### Request Example ```typescript import { reviewsClient } from 'lib/reviews/client' const reviews = await reviewsClient.getProductReviews() ``` ### Response #### Success Response - **JudgeClient** - A client object with review methods. ### Source `lib/reviews/client.ts:120-130` ``` -------------------------------- ### Get hierarchical Shopify collections Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/shopify.md Retrieve collections structured as a hierarchical menu. Specify the menu handle and optionally the desired depth for nesting. ```typescript const menu = await client.getHierarchicalCollections('main-menu', 4) console.log(menu.items) // Nested menu structure ``` -------------------------------- ### ProductEnrichmentBuilder.build Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/utilities.md Finalize the enrichment and return the product. ```APIDOC ## build ### Description Finalize the enrichment and return the product. ### Returns Enriched product with all applied fields ``` -------------------------------- ### Get All Published Reviews Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/algolia.md Retrieves all published and non-hidden reviews from the index. This is useful for aggregating review data or displaying a general overview of reviews. ```typescript import { getAllReviews } from 'lib/algolia' const { reviews, totalPages } = await getAllReviews({ attributesToRetrieve: ['rating', 'body', 'product_handle'] }) ``` -------------------------------- ### Retrieve Navigation Items Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/endpoints.md Fetches the application's navigation structure. The response is cached for 360 seconds. ```bash curl https://example.com/api/navigation # Response: { "items": [...] } ``` -------------------------------- ### Get a Single Collection by Handle Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/algolia.md Retrieves a specific collection using its unique handle. Use this when you need to display details for a single category. ```typescript import { getCollection } from 'lib/algolia' const category = await getCollection('summer-collection') if (category) { console.log(category.title, category.descriptionHtml) } ``` -------------------------------- ### Import and use cached Shopify functions Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/shopify.md Demonstrates importing and using cached Shopify client functions, such as getProduct and createCart, from the 'lib/shopify' path. ```typescript import { getProduct, createCart } from 'lib/shopify' const product = await getProduct('gid://shopify/Product/123') const cart = await createCart([]) ``` -------------------------------- ### Get Single Mock Category by Handle for Demo Mode Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/utilities.md Retrieves a single mock category by its handle (slug), used in demo mode. ```typescript getDemoSingleCategory(slug: string): PlatformCollection | null ``` -------------------------------- ### Perform a full product feed sync Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/shopify.md Executes a full synchronization for a specified product feed. Requires the product feed ID as a parameter. ```typescript fullSyncProductFeed(id: string): Promise ``` ```typescript const syncResult = await client.fullSyncProductFeed('feed-123') ``` -------------------------------- ### Get Mock Category Data for Demo Mode Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/utilities.md Retrieves mock category data, typically used when the application is running in demo mode. ```typescript getDemoCategories(): { hits: PlatformCollection[] } ``` -------------------------------- ### Generate AI Alt Tags for Product Images Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/utilities.md Use `withAltTags` to asynchronously generate AI-powered alt text for product images. Ensure Replicate AI API credentials are set and the feature is opted-in. ```typescript const enriched = await new ProductEnrichmentBuilder(product) .withAltTags() .build() console.log(enriched.images[0].altText) // AI-generated description ``` -------------------------------- ### createShopifyClient Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/shopify.md Factory function to create a Shopify client instance. It requires the store domain and optionally accepts storefront and admin access tokens. ```APIDOC ## createShopifyClient ### Description Factory function to create a Shopify client instance. It requires the store domain and optionally accepts storefront and admin access tokens. ### Method Factory Function ### Parameters #### Path Parameters - **storeDomain** (string) - Required - Shopify store domain (e.g., 'mystore.myshopify.com') - **storefrontAccessToken** (string) - Optional - Storefront API access token for public queries - **adminAccessToken** (string) - Optional - Admin API access token for admin mutations ### Returns `ShopifyClient` — A client object with all methods. ### Example ```typescript import { createShopifyClient } from 'lib/shopify/client' const client = createShopifyClient({ storeDomain: 'mystore.myshopify.com', storefrontAccessToken: 'abcd1234...', adminAccessToken: 'shpat_xyz...' }) const product = await client.getProduct('Z2lkOi8vU2hvcGlmeS9Qcm9kdWN0LzEuanNvbg==') ``` ``` -------------------------------- ### GET /api/health Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/endpoints.md Provides a basic health check for the application. It returns a simple JSON object indicating the service's operational status. ```APIDOC ## GET /api/health ### Description Basic health check endpoint to verify service availability. ### Method GET ### Endpoint /api/health ### Response #### Success Response (200) - **status** (string) - Indicates the service is healthy, typically "ok". #### Response Example { "status": "ok" } ``` -------------------------------- ### Environment Variables for Deployment Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/README.md Lists essential environment variables required for deploying the application, including Shopify and Algolia credentials, and a cron secret. These variables are crucial for connecting to external services and enabling core functionalities. ```shell SHOPIFY_STORE_DOMAIN SHOPIFY_STOREFRONT_ACCESS_TOKEN SHOPIFY_ADMIN_ACCESS_TOKEN SHOPIFY_APP_API_SECRET_KEY ALGOLIA_APPLICATION_ID ALGOLIA_API_KEY ALGOLIA_PRODUCTS_INDEX ALGOLIA_CATEGORIES_INDEX CRON_SECRET ``` -------------------------------- ### createProductReview Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/reviews.md Creates a new product review. This is a server action wrapper for review creation. ```APIDOC ## createProductReview ### Description Creates a new product review. This is a server action wrapper for review creation. ### Method Not specified (likely a POST request or SDK method call) ### Endpoint Not specified ### Parameters #### Request Body - **name** (string) - Required - Reviewer's name. - **email** (string) - Required - Reviewer's email address. - **rating** (1 | 2 | 3 | 4 | 5) - Required - Star rating for the product. - **body** (string) - Required - The text content of the review. - **id** (string) - Required - The unique identifier of the product. - **ip_addr** (string | null) - Optional - The IP address of the reviewer. ### Request Example ```json { "name": "Alice", "email": "alice@example.com", "rating": 4, "body": "Very good product!", "id": "product-123", "ip_addr": "10.0.0.1" } ``` ### Response #### Success Response - **any** - The response type is not explicitly defined, but it indicates success. ### Response Example ```json { "message": "Review created successfully" } ``` ``` -------------------------------- ### fullSyncProductFeed Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/shopify.md Performs a full product feed sync using the provided product feed ID. It returns a promise with the sync response. ```APIDOC ## fullSyncProductFeed ### Description Perform a full product feed sync. ### Method POST ### Endpoint /shopify/product-feed/{id}/sync ### Parameters #### Path Parameters - **id** (string) - Required - Product feed ID ### Returns `Promise` — Sync response. ### Example ```typescript const syncResult = await client.fullSyncProductFeed('feed-123') ``` ``` -------------------------------- ### Get Shopify Collection by GraphQL ID Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/shopify.md Retrieve a collection using its unique Shopify GraphQL ID. Returns a collection object or null if the collection does not exist. ```typescript const collection = await client.getCollectionById('gid://shopify/Collection/456789') ``` -------------------------------- ### createProductFeed Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/shopify.md Creates a new product feed for bulk data export. It returns a promise that resolves with the feed ID. ```APIDOC ## createProductFeed ### Description Create a new product feed for bulk data export. ### Method POST ### Endpoint /shopify/product-feed ### Returns `Promise` — Feed creation response with feed ID. ### Example ```typescript const feed = await client.createProductFeed() console.log(feed.id) // Feed ID for polling status ``` ``` -------------------------------- ### Get Algolia Facet Values Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/algolia.md Retrieves all unique values for a specified facet from an Algolia index. Ensure the index name and facet name are correctly provided. ```typescript import { getFacetValues } from 'lib/algolia' const vendors = await getFacetValues({ indexName: 'products', facetName: 'vendor' }) console.log(vendors) // ['Nike', 'Adidas', 'Puma', ...] ``` -------------------------------- ### Image Optimization with useResponsiveCarousel Config Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/hooks.md Demonstrates how to use the `config` object returned by `useResponsiveCarousel` to optimize image rendering. It applies the `quality` and `sizes` properties to an `Image` component. ```typescript const { config } = useResponsiveCarousel() {image.altText} ``` -------------------------------- ### Convert Currency Code to Symbol Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/utilities.md Converts an ISO 4217 currency code into its corresponding currency symbol. Examples include USD to '$', EUR to '€', and GBP to '£'. ```typescript import { mapCurrencyToSign } from 'utils/map-currency-to-sign' mapCurrencyToSign('USD') // "$" mapCurrencyToSign('EUR') // "€" mapCurrencyToSign('GBP') // "£" ``` -------------------------------- ### ProductEnrichmentBuilder.withReviews Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/utilities.md Add review statistics to product. ```APIDOC ## withReviews ### Description Add review statistics to product. ### Parameters #### Path Parameters - `allReviews` (Review[]) - Required - All reviews to filter by product ### Returns `this` (for chaining) ### Adds fields - `avgRating` — Average rating across published reviews - `totalReviews` — Count of published, non-hidden reviews ### Example ```typescript import { getAllProductReviews } from 'lib/reviews' const reviews = await getAllProductReviews() const enriched = new ProductEnrichmentBuilder(product) .withReviews(reviews) .build() console.log(enriched.avgRating, enriched.totalReviews) ``` ``` -------------------------------- ### Get Algolia Products by Collection Tag Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/algolia.md Fetches products associated with a specific tag or collection tag. An optional limit can be set to control the number of returned products. ```typescript import { getProductsByCollectionTag } from 'lib/algolia' const newArrivals = await getProductsByCollectionTag('new-arrivals', 20) console.log(newArrivals) // Up to 20 products with the tag ``` -------------------------------- ### getAllProductReviews Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/reviews.md Retrieve all product reviews, handling pagination automatically. Returns a promise that resolves to an array of all reviews. ```APIDOC ## getAllProductReviews ### Description Retrieve all product reviews, handling pagination automatically. ### Method Client Method ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const allReviews = await client.getAllProductReviews() ``` ### Response #### Success Response - **Review[]** - All reviews across all pages. ### Source `lib/reviews/client.ts:58-70` ``` -------------------------------- ### buildCategoryMap Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/utilities.md Build a map of collection handles to their hierarchical paths. ```APIDOC ## buildCategoryMap ### Description Build a map of collection handles to their hierarchical paths. ### Parameters #### Path Parameters - `items` (PlatformMenu["items"]) - Required - Menu items from getMenu() ### Returns Map where key is collection handle and value is path array. ### Example ```typescript import { buildCategoryMap } from 'utils/enrich-product' const map = buildCategoryMap(menuItems) // Map: // { // "men" => ["men"], // "shirts" => ["men", "shirts"], // "casual" => ["men", "shirts", "casual"] // } ``` ``` -------------------------------- ### Notify User About Disabled Feature and Prompt Enablement Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/utilities.md Sends a notification about a disabled feature and provides a URL to enable it. Useful for guiding users through feature enablement flows. ```typescript import { notifyOptIn } from 'utils/opt-in' if (!isOptIn('reviews')) { notifyOptIn({ feature: 'reviews', source: 'product.page' }) } ``` -------------------------------- ### PlatformUserCreateInput Interface Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/types.md Defines the required and optional fields for creating or updating a customer account, including email, password, and name. ```typescript interface PlatformUserCreateInput { email: string password?: string firstName?: string lastName?: string } ``` -------------------------------- ### Create User Access Token Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/shopify.md Generates an access token for customer login. Requires an object with the customer's email and password. ```typescript const tokenData = await client.createUserAccessToken({ email: 'john@example.com', password: 'secure123!' }) console.log(tokenData.accessToken) ``` -------------------------------- ### Shopify to Algolia Sync Process Flowchart Source: https://github.com/blazity/enterprise-commerce/blob/main/starters/shopify-algolia/scripts/sync/README.md Visual representation of the data synchronization process from Shopify to Algolia, including delta calculation and batch operations. ```mermaid flowchart TB subgraph Shopify direction TB ShopifyProducts[Shopify Products] ShopifyCategories[Shopify Categories] ShopifyReviews["Shopify Reviews (JudgeMe)"] end subgraph Algolia direction TB AlgoliaProducts[Algolia Products Index] AlgoliaCategories[Algolia Categories Index] AlgoliaReviews[Algolia Reviews Index] end ShopifyProducts --> Delta[Delta Calculation] ShopifyCategories --> Delta ShopifyReviews --> Delta AlgoliaProducts --> Delta AlgoliaCategories --> Delta AlgoliaReviews --> Delta Delta --> BatchUpdate[Batch Update] Delta --> Obsolete[Obsolete IDs] Obsolete --> BatchDelete[Batch Delete] ``` -------------------------------- ### Home Page A/B Testing Buckets Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/configuration.md Configuration for A/B testing on the home page. Defines the variants available for user assignment using the `getBucket` function. ```typescript export const BUCKETS = { HOME: ["a", "b"], } ``` -------------------------------- ### Get List of Favorite Product Handles Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/server-actions.md Retrieves an array of product handles that the user has favorited. This action is useful for displaying a user's favorite items or checking if a product is already favorited. ```typescript getParsedFavoritesHandles(): Promise ``` ```typescript import { getParsedFavoritesHandles } from 'app/actions/favorites.actions' const favorites = await getParsedFavoritesHandles() console.log(`Favorited ${favorites.length} products`) ``` -------------------------------- ### Retrieve a Shopify page by handle Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/shopify.md Fetches a specific page using its unique handle. Returns the page object or null if not found. ```typescript const aboutPage = await client.getPage('about-us') console.log(aboutPage?.bodySummary) ``` -------------------------------- ### Get Shopify Admin Product Data Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/shopify.md Fetch raw product data from the Admin API using the product ID (without the 'gid://' prefix). This provides access to additional fields not available in Storefront API. ```typescript const adminProduct = await client.getAdminProduct('123456789') console.log(adminProduct.feedStatus) ``` -------------------------------- ### createJudgeClient Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/reviews.md Factory function to create a Judge.me API client. It requires the base URL, an API key for authentication, and the shop domain. ```APIDOC ## createJudgeClient ### Description Factory function to create a Judge.me API client. ### Method Factory Function ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **baseUrl** (string) - Yes - Judge.me API base URL (e.g., 'https://api.judge.me/v1') - **apiKey** (string) - Yes - Judge.me API key for authentication - **shopDomain** (string) - Yes - Shopify store domain ### Request Example ```typescript import { createJudgeClient } from 'lib/reviews/client' const client = createJudgeClient({ baseUrl: 'https://api.judge.me/v1', apiKey: 'your-api-key', shopDomain: 'mystore.myshopify.com' }) ``` ### Response #### Success Response - **JudgeClient** - A client object with review methods. ### Source `lib/reviews/client.ts:18-28` ``` -------------------------------- ### Create Judge.me API Client Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/reviews.md Use this factory function to initialize a Judge.me API client. Provide your API key, shop domain, and the base URL for the Judge.me API. ```typescript import { createJudgeClient } from 'lib/reviews/client' const client = createJudgeClient({ baseUrl: 'https://api.judge.me/v1', apiKey: 'your-api-key', shopDomain: 'mystore.myshopify.com' }) const reviews = await client.getProductReviews({ product_external_id: 123456 }) ``` -------------------------------- ### getBucket Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/utilities.md Assigns a user to an A/B test bucket. This function randomly distributes users across predefined buckets for experimentation. ```APIDOC ## getBucket ### Description Assign a user to an A/B test bucket. ### Method Not applicable (TypeScript function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **buckets** (readonly string[]) - Required - Array of bucket names ### Request Example ```typescript import { getBucket } from 'utils/ab-testing' import { BUCKETS } from 'constants' const bucket = getBucket(BUCKETS.HOME) // Returns: 'a' or 'b' with 50% probability each if (bucket === 'a') { // Show variant A } else { // Show variant B } ``` ### Response #### Success Response - **string** (string) - One of the bucket names, randomly distributed #### Response Example ``` "a" ``` ### Probability Each bucket has equal probability (100 / buckets.length %) ### Uses Cryptographically secure random numbers (crypto.getRandomValues) ``` -------------------------------- ### getSimilarProducts Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/algolia.md Finds products that are similar to a given product using AI-powered recommendations. Requires a collection and the objectID of the target product. ```APIDOC ## getSimilarProducts ### Description Finds products that are similar to a given product using AI-powered recommendations. Requires a collection and the objectID of the target product. ### Method ```typescript getSimilarProducts(collection: string | undefined, objectID: string): Promise ``` ### Parameters #### Path Parameters - **collection** (string | undefined) - Required - The collection handle to search within; if undefined returns empty array. - **objectID** (string) - Required - The Algolia objectID of the product to find similar items for. ### Response #### Success Response - **CommerceProduct[]** - Array of similar products (up to 8 items). ### Request Example ```typescript import { getSimilarProducts } from 'lib/algolia' const similar = await getSimilarProducts('clothing', 'product-123') console.log(similar) // Up to 8 similar products ``` ``` -------------------------------- ### Add Review Statistics to Product Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/utilities.md Use `withReviews` to add average rating and total review count to a product. Provide all reviews to filter by the current product. ```typescript import { getAllProductReviews } from 'lib/reviews' const reviews = await getAllProductReviews() const enriched = new ProductEnrichmentBuilder(product) .withReviews(reviews) .build() console.log(enriched.avgRating, enriched.totalReviews) ``` -------------------------------- ### getProductByHandle Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/shopify.md Retrieve a product by its handle (URL-friendly identifier). Returns a normalized product object or null if not found. ```APIDOC ## getProductByHandle ### Description Retrieve a product by its handle (URL-friendly identifier). Returns a normalized product object or null if not found. ### Method `getProductByHandle(handle: string): Promise` ### Parameters #### Path Parameters - **handle** (string) - Required - Product handle (URL-friendly identifier) ### Returns `Promise` — Normalized product object or null. ### Example ```typescript const product = await client.getProductByHandle('blue-cotton-shirt') console.log(product?.variants) // All available variants ``` ``` -------------------------------- ### makeKeywords Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/utilities.md Extracts searchable keywords from product text, such as descriptions or titles. Returns an array of individual words. ```APIDOC ## makeKeywords ### Description Extract searchable keywords from product text. ### Signature ```typescript makeKeywords(text: string): string[] ``` ### Parameters #### Path Parameters - **text** (string) - Required - Product description or title ### Returns Array of individual words suitable for search. ``` -------------------------------- ### getDemoSingleProduct Source: https://github.com/blazity/enterprise-commerce/blob/main/_autodocs/api-reference/utilities.md Retrieves a single mock product by its handle, typically used when the application is in demo mode. ```APIDOC ## getDemoSingleProduct ### Description Get a single mock product by handle. ### Signature ```typescript getDemoSingleProduct(handle: string): CommerceProduct | null ``` ### Parameters #### Path Parameters - **handle** (string) - Required - The handle of the product to retrieve. ### Returns A single `CommerceProduct` object or `null` if not found. ```