### 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 (