### Front-Commerce Project Initialization and Setup Source: https://context7.com/context7/developers_front-commerce_3_x/llms.txt Commands to initialize a new Front-Commerce project, navigate to the project directory, install dependencies, configure environment variables via a .env file, and start the development server. ```bash # Initialize a new Front-Commerce project npx create-front-commerce-app my-shop # Navigate to project directory cd my-shop # Install dependencies npm install # Configure environment variables cat > .env << EOF FRONT_COMMERCE_BACKEND_URL=https://api.example.com FRONT_COMMERCE_CACHE_API_TOKEN=your_cache_token FRONT_COMMERCE_GRAPHQL_ENDPOINT=/graphql FRONT_COMMERCE_ENV=development EOF # Start development server npm run dev # Server runs at http://localhost:4000 ``` -------------------------------- ### GraphQL Schema and Resolver Examples Source: https://context7.com/context7/developers_front-commerce_3_x/llms.txt Defines a GraphQL schema for products and associated queries, along with an example resolver function that integrates with commerce and ERP APIs to fetch product data and inventory. This showcases the data aggregation capabilities. ```graphql type Product { id: ID! sku: String! name: String! price: Money! description: String images: [Image!]! availability: Stock! categories: [Category!]! } type Query { product(id: ID!): Product products(categoryId: ID, limit: Int, offset: Int): ProductConnection } ``` ```javascript const resolvers = { Query: { product: async (_, { id }, { dataSources }) => { const productData = await dataSources.commerceAPI.getProduct(id); const inventory = await dataSources.erpAPI.getInventory(productData.sku); return { ...productData, availability: inventory, }; }, }, }; ``` -------------------------------- ### React Component for Product Listing Source: https://context7.com/context7/developers_front-commerce_3_x/llms.txt An example React component demonstrating how to fetch and display a list of products using Apollo Client for data fetching and Front-Commerce UI components. It handles loading and error states. ```jsx import { useQuery } from '@apollo/client'; import { ProductCard } from '@front-commerce/ui'; const ProductList = ({ categoryId }) => { const { data, loading, error } = useQuery(GET_PRODUCTS, { variables: { categoryId }, }); if (loading) return ; if (error) return ; return (
{data.products.map(product => ( ))}
); }; ``` -------------------------------- ### Test React Components with Jest and React Testing Library Source: https://context7.com/context7/developers_front-commerce_3_x/llms.txt Provides example unit tests for a React `ProductCard` component using Jest and React Testing Library. It covers rendering component information, checking conditional rendering (e.g., 'Out of Stock'), verifying link attributes, and asserting custom data attributes for tracking. Dependencies include 'react', '@testing-library/react', and 'react-router-dom'. ```jsx import React from 'react'; import { render, screen, fireEvent } from '@testing-library/react'; import { BrowserRouter } from 'react-router-dom'; import ProductCard from '../ProductCard'; describe('ProductCard', () => { const mockProduct = { id: '1', name: 'Test Product', price: { amount: 29.99, currency: 'USD', formatted: '$29.99' }, image: { url: '/test.jpg', alt: 'Test Product' }, url: '/products/test-product', availability: { inStock: true }, }; const renderProductCard = (product = mockProduct) => { return render( ); }; it('renders product information correctly', () => { renderProductCard(); expect(screen.getByText('Test Product')).toBeInTheDocument(); expect(screen.getByText('$29.99')).toBeInTheDocument(); expect(screen.getByAltText('Test Product')).toHaveAttribute('src', '/test.jpg'); }); it('displays out of stock badge when unavailable', () => { const outOfStockProduct = { ...mockProduct, availability: { inStock: false }, }; renderProductCard(outOfStockProduct); expect(screen.getByText('Out of Stock')).toBeInTheDocument(); }); it('links to product detail page', () => { renderProductCard(); const link = screen.getByRole('link'); expect(link).toHaveAttribute('href', '/products/test-product'); }); it('includes product data attribute for tracking', () => { const { container } = renderProductCard(); const article = container.querySelector('article'); expect(article).toHaveAttribute('data-product-id', '1'); }); }); ``` -------------------------------- ### Front-Commerce Production Build and Deployment Script Source: https://context7.com/context7/developers_front-commerce_3_x/llms.txt Outlines the process for building a production-ready bundle of the Front-Commerce application, configuring necessary environment variables, and running the production server. It utilizes npm for building and Node.js for execution, with a health check endpoint. ```bash # Build production bundle npm run build # Output structure: dist/ ├── client/ # Client-side bundles │ ├── main.[hash].js │ ├── vendors.[hash].js │ └── assets/ ├── server/ # Server-side bundles │ └── index.js └── public/ # Static assets # Environment configuration for production cat > .env.production << EOF NODE_ENV=production FRONT_COMMERCE_URL=https://www.mystore.com FRONT_COMMERCE_BACKEND_URL=https://api.mystore.com FRONT_COMMERCE_CACHE_API_TOKEN=prod_cache_token FRONT_COMMERCE_CACHE_TTL=3600 FRONT_COMMERCE_ENABLE_SOURCE_MAPS=false FRONT_COMMERCE_ASSET_CDN=https://cdn.mystore.com EOF # Run production server NODE_ENV=production node dist/server/index.js # Health check endpoint curl http://localhost:4000/health # Response: {"status":"ok","version":"3.0.0","uptime":12345} ``` -------------------------------- ### Dockerizing Front-Commerce for Production Deployment Source: https://context7.com/context7/developers_front-commerce_3_x/llms.txt Provides a Dockerfile to containerize the Front-Commerce application, ensuring consistent deployment across environments. It includes multi-stage builds for optimization, dependency management, and setting up a production-ready image with a non-root user and health check. ```dockerfile # Dockerfile for Front-Commerce application FROM node:18-alpine AS builder WORKDIR /app # Copy package files COPY package*.json ./ COPY .npmrc ./ # Install dependencies RUN npm ci --only=production && npm cache clean --force # Copy application code COPY . . # Build application RUN npm run build # Production image FROM node:18-alpine WORKDIR /app # Copy built application and dependencies COPY --from=builder /app/dist ./dist COPY --from=builder /app/node_modules ./node_modules COPY --from=builder /app/package.json ./ # Create non-root user RUN addgroup -g 1001 -S nodejs && \ adduser -S frontcommerce -u 1001 USER frontcommerce EXPOSE 4000 # Health check HEALTHCHECK --interval=30s --timeout=3s --start-period=40s \ CMD node -e "require('http').get('http://localhost:4000/health', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})" CMD ["node", "dist/server/index.js"] ``` -------------------------------- ### Docker Compose Commands for Front-Commerce Development Source: https://context7.com/context7/developers_front-commerce_3_x/llms.txt Provides essential commands for managing the Front-Commerce local development environment using Docker Compose. These commands cover deploying services, viewing logs, and scaling application instances. ```bash # Deploy with: docker-compose up -d # View logs: docker-compose logs -f front-commerce # Scale instances: docker-compose up -d --scale front-commerce=3 ``` -------------------------------- ### React Integration Testing with GraphQL Mocks Source: https://context7.com/context7/developers_front-commerce_3_x/llms.txt Demonstrates how to test React components that consume GraphQL APIs using mock responses provided by Apollo Client's MockedProvider. It covers rendering the component, simulating loading states, displaying data, and handling errors, with dependencies on React, @apollo/client/testing, and react-router-dom. ```jsx // src/web/theme/pages/__tests__/ProductPage.test.js import React from 'react'; import { render, screen, waitFor } from '@testing-library/react'; import { MockedProvider } from '@apollo/client/testing'; import { MemoryRouter, Route, Routes } from 'react-router-dom'; import ProductPage from '../ProductPage'; import { GET_PRODUCT_DETAILS } from '../ProductPage'; describe('ProductPage', () => { const mockProductData = { product: { id: '1', sku: 'TEST-SKU-001', name: 'Test Product', description: 'A test product description', price: { amount: 29.99, currency: 'USD', formatted: '$29.99', }, images: [ { url: '/image1.jpg', alt: 'Test Product' }, ], availability: { inStock: true, quantity: 10, }, categories: [ { id: 'cat1', name: 'Category 1', url: '/category-1' }, ], }, }; const mocks = [ { request: { query: GET_PRODUCT_DETAILS, variables: { id: '1' }, }, result: { data: mockProductData, }, }, ]; const errorMocks = [ { request: { query: GET_PRODUCT_DETAILS, variables: { id: '1' }, }, error: new Error('Network error'), }, ]; const renderProductPage = (mocks) => { return render( } /> ); }; it('displays loading state initially', () => { renderProductPage(mocks); expect(screen.getByTestId('product-skeleton')).toBeInTheDocument(); }); it('displays product details after loading', async () => { renderProductPage(mocks); await waitFor(() => { expect(screen.getByText('Test Product')).toBeInTheDocument(); }); expect(screen.getByText('SKU: TEST-SKU-001')).toBeInTheDocument(); expect(screen.getByText('$29.99')).toBeInTheDocument(); expect(screen.getByText('A test product description')).toBeInTheDocument(); }); it('displays error message on fetch failure', async () => { renderProductPage(errorMocks); await waitFor(() => { expect(screen.getByText('Unable to load product details')).toBeInTheDocument(); }); }); }); ``` -------------------------------- ### Fetch Product Data with Apollo Client Hooks Source: https://context7.com/context7/developers_front-commerce_3_x/llms.txt Demonstrates how to use Apollo Client's `useQuery` hook to fetch product details from a GraphQL server. It includes state management for loading, errors, and displaying product information. Dependencies: `@apollo/client`, `react-router-dom`. ```jsx // src/web/theme/pages/ProductPage.js import React from 'react'; import { useQuery, gql } from '@apollo/client'; import { useParams } from 'react-router-dom'; const GET_PRODUCT_DETAILS = gql` query GetProduct($id: ID!) { product(id: $id) { id sku name description price { amount currency formatted } images { url alt } availability { inStock quantity } categories { id name url } } } `; const ProductPage = () => { const { productId } = useParams(); const { data, loading, error, refetch } = useQuery(GET_PRODUCT_DETAILS, { variables: { id: productId }, errorPolicy: 'all', }); if (loading) { return ; } if (error) { return ( ); } const { product } = data; return (

{product.name}

SKU: {product.sku}

{product.price.formatted}

{product.description}
); }; export default ProductPage; ``` -------------------------------- ### Docker Compose Configuration for Front-Commerce Local Development Source: https://context7.com/context7/developers_front-commerce_3_x/llms.txt This configuration defines the services, ports, environment variables, dependencies, and health checks for running Front-Commerce and its Redis dependency locally using Docker Compose. It specifies build context for the front-commerce service and uses a pre-built Redis image. ```yaml version: '3.8' services: front-commerce: build: . ports: - "4000:4000" environment: - NODE_ENV=production - FRONT_COMMERCE_URL=http://localhost:4000 - FRONT_COMMERCE_BACKEND_URL=http://api:8080 - REDIS_URL=redis://redis:6379 depends_on: - redis restart: unless-stopped healthcheck: test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost:4000/health"] interval: 30s timeout: 10s retries: 3 redis: image: redis:7-alpine ports: - "6379:6379" volumes: - redis-data:/data restart: unless-stopped volumes: redis-data: ``` -------------------------------- ### Configure Backend Integration with JavaScript Source: https://context7.com/context7/developers_front-commerce_3_x/llms.txt This configuration file sets up Front-Commerce to connect with various backend systems like Magento2 and Contentful. It defines module paths and server module configurations, essential for backend integration. ```javascript // front-commerce.config.js module.exports = { name: "My E-commerce Store", url: "https://www.mystore.com", modules: [ "./node_modules/@front-commerce/magento2", "./node_modules/@front-commerce/contentful", "./src/custom", ], serverModules: [ { name: "Magento2", path: "@front-commerce/magento2/server" }, { name: "Contentful", path: "@front-commerce/contentful/server" }, ], webModules: [ { name: "FrontCommerce", path: "./src/web" }, ], }; // Example backend data source configuration // src/server/modules/datasources/commerce.js class CommerceDataSource extends RESTDataSource { constructor() { super(); this.baseURL = process.env.COMMERCE_API_URL; } willSendRequest(request) { request.headers.set('Authorization', `Bearer ${this.context.token}`); } async getProduct(id) { try { const response = await this.get(`/products/${id}`); return this.transformProduct(response); } catch (error) { throw new Error(`Failed to fetch product ${id}: ${error.message}`); } } transformProduct(rawProduct) { return { id: rawProduct.id, sku: rawProduct.sku, name: rawProduct.name, price: { amount: rawProduct.price, currency: rawProduct.currency || 'USD', }, images: rawProduct.images.map(img => ({ url: img.url, alt: img.alt || rawProduct.name, })), }; } } ``` -------------------------------- ### Develop Custom UI Component with React and Storybook Source: https://context7.com/context7/developers_front-commerce_3_x/llms.txt This code demonstrates building a reusable 'ProductCard' UI component using React. It includes Storybook stories for development and testing, showcasing different states like 'In Stock' and 'Out of Stock'. ```jsx // src/web/theme/components/ProductCard/ProductCard.js import React from 'react'; import { Link } from 'react-router-dom'; import { FormattedPrice } from '@front-commerce/ui'; import { Image } from '@front-commerce/ui'; const ProductCard = ({ product }) => { const { id, name, price, image, url, availability } = product; return (
{image.alt {!availability.inStock && ( Out of Stock )}

{name}

); }; export default ProductCard; // Storybook story for component development // src/web/theme/components/ProductCard/ProductCard.stories.js export default { title: 'Components/ProductCard', component: ProductCard, }; export const InStock = { args: { product: { id: '1', name: 'Premium T-Shirt', price: { amount: 29.99, currency: 'USD' }, image: { url: '/images/tshirt.jpg', alt: 'Premium T-Shirt' }, url: '/products/premium-tshirt', availability: { inStock: true }, }, }, }; export const OutOfStock = { args: { product: { id: '2', name: 'Limited Edition Hoodie', price: { amount: 79.99, currency: 'USD' }, image: { url: '/images/hoodie.jpg', alt: 'Limited Edition Hoodie' }, url: '/products/limited-hoodie', availability: { inStock: false }, }, }, }; ``` -------------------------------- ### Implement Code Splitting and Lazy Loading in React Router Source: https://context7.com/context7/developers_front-commerce_3_x/llms.txt Demonstrates code splitting and lazy loading of React components using dynamic imports with React Router v6. It utilizes `React.lazy` and `Suspense` to improve initial page load performance. This pattern is essential for managing large application bundles. ```jsx import React, { lazy, Suspense } from 'react'; import { Route, Routes } from 'react-router-dom'; import LoadingSpinner from '../components/LoadingSpinner'; // Lazy load route components const HomePage = lazy(() => import('../pages/HomePage')); const ProductPage = lazy(() => import('../pages/ProductPage')); const CategoryPage = lazy(() => import('../pages/CategoryPage')); const CartPage = lazy(() => import('../pages/CartPage')); const CheckoutPage = lazy(() => import('../pages/CheckoutPage')); const AppRoutes = () => { return ( }> } /> } /> } /> } /> }> } /> ); }; // Example of dynamic import for heavy components const ProductReviews = ({ productId }) => { const [ReviewsComponent, setReviewsComponent] = React.useState(null); React.useEffect(() => { // Only load reviews component when needed import('../components/ProductReviews').then((module) => { setReviewsComponent(() => module.default); }); }, []); if (!ReviewsComponent) { return
Loading reviews...
; } return ; }; export default AppRoutes; ``` -------------------------------- ### Configure SSR with Caching in Express.js Source: https://context7.com/context7/developers_front-commerce_3_x/llms.txt Sets up Server-Side Rendering (SSR) middleware in an Express.js application using Front-Commerce. It includes configuration for caching strategies, cache invalidation based on headers, and performance monitoring. Dependencies include 'express' and '@front-commerce/core/server'. ```javascript import express from 'express'; import { createSSRMiddleware } from '@front-commerce/core/server'; const app = express(); // Configure SSR middleware with caching app.use( createSSRMiddleware({ // Cache configuration for performance cache: { strategy: 'render', ttl: 60 * 60, // 1 hour in seconds varyByHeaders: ['accept-language', 'accept-encoding'], }, // Performance monitoring onRenderComplete: ({ duration, url, cached }) => { console.log(`SSR ${cached ? 'cache hit' : 'render'}: ${url} (${duration}ms)`); }, }) ); // Example custom middleware for performance headers app.use((req, res, next) => { // Add cache control headers if (req.path.startsWith('/products/')) { res.set('Cache-Control', 'public, max-age=300, s-maxage=3600'); } next(); }); app.listen(4000, () => { console.log('Front-Commerce server running on http://localhost:4000'); }); ``` -------------------------------- ### Implement Add to Cart Mutation with Optimistic Updates Source: https://context7.com/context7/developers_front-commerce_3_x/llms.txt Shows how to perform a GraphQL mutation to add items to the cart using Apollo Client's `useMutation` hook. It includes optimistic UI updates, error handling, and cache management. Dependencies: `@apollo/client`, `react`. ```jsx // src/web/theme/modules/Cart/AddToCart.js import React, { useState } from 'react'; import { useMutation, gql } from '@apollo/client'; const ADD_TO_CART = gql` mutation AddToCart($productId: ID!, $quantity: Int!) { addToCart(input: { productId: $productId, quantity: $quantity }) { cart { id itemCount items { id product { id name } quantity price { amount currency } } } userErrors { field message } } } `; const AddToCartButton = ({ product, quantity = 1 }) => { const [isAdding, setIsAdding] = useState(false); const [addToCart, { error }] = useMutation(ADD_TO_CART, { onCompleted: (data) => { if (data.addToCart.userErrors.length === 0) { setIsAdding(false); // Show success notification showNotification({ type: 'success', message: `${product.name} added to cart`, }); } }, onError: (error) => { setIsAdding(false); showNotification({ type: 'error', message: 'Failed to add item to cart', }); }, // Optimistic update for instant UI feedback optimisticResponse: { addToCart: { __typename: 'AddToCartPayload', cart: { __typename: 'Cart', id: 'temp', itemCount: quantity, items: [], }, userErrors: [], }, }, // Update cache to reflect new cart state update: (cache, { data }) => { if (data.addToCart.cart) { cache.modify({ fields: { cart: () => data.addToCart.cart, }, }); } }, }); const handleAddToCart = async () => { setIsAdding(true); try { await addToCart({ variables: { productId: product.id, quantity, }, }); } catch (err) { console.error('Add to cart error:', err); } }; return ( ); }; export default AddToCartButton; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.