Skip to content

Siwakrit/CATALOG-API

Repository files navigation

πŸͺ Catalog API - Enterprise Multi-Tenant E-commerce Platform

Node.js NestJS TypeScript PostgreSQL Docker License

A comprehensive, enterprise-grade REST API for multi-tenant e-commerce platforms with advanced features including internationalization, content management, and AWS S3 integration.

✨ Core Features & Capabilities

🏒 Multi-Tenant Architecture

  • Tenant Isolation: Complete data separation between organizations
  • Subdomain Routing: Automatic tenant detection via subdomains
  • Scalable Design: Support for unlimited tenants with optimized queries
  • Admin Panel: Cross-tenant administration and management

πŸ” Advanced Authentication & Authorization

  • JWT Authentication: Secure token-based authentication
  • Role-Based Access Control (RBAC): Granular permission management
  • Multi-Factor Authentication: Enhanced security options
  • Session Management: Secure refresh token handling

🌐 Internationalization (i18n)

  • Multi-language Support: Dynamic language switching
  • Content Translation: Database-level translation system
  • Locale Management: Automated language detection
  • Translation APIs: RESTful endpoints for content management

πŸ“¦ Product & Catalog Management

  • Product Management: Complete product lifecycle
  • Category Hierarchy: Nested categories with translations
  • Inventory Tracking: Real-time stock management
  • Price Management: Multi-currency support
  • SEO Optimization: Meta tags and URL optimization

πŸ“„ Content Management System (CMS)

  • Blog System: Full-featured blog with translations
  • Page Management: Dynamic page creation and editing
  • Media Library: Integrated file management
  • Template System: Customizable content templates

πŸ—„οΈ File Management & Storage

  • AWS S3 Integration: Scalable cloud storage
  • Local Storage: Development-friendly file handling
  • Image Processing: Automatic image optimization
  • File Validation: Security-focused upload handling

πŸ”§ Technical Features

  • RESTful API: Complete REST API with OpenAPI documentation
  • Database Migrations: Version-controlled schema management
  • Comprehensive Logging: Structured logging with rotation
  • Health Checks: Built-in monitoring endpoints
  • Error Handling: Standardized error responses
  • Rate Limiting: API protection and throttling

πŸš€ Quick Start Guide

System Requirements

Component Version Required
Node.js 18.0+ βœ… Yes
npm/yarn Latest βœ… Yes
PostgreSQL 15.0+ βœ… Yes
Docker 20.0+ πŸ”„ Optional
Docker Compose 2.0+ πŸ”„ Optional

1. Repository Setup

# Clone the repository
git clone https://github.com/yourusername/catalog-api.git
cd catalog-api

# Install dependencies
npm install

2. Environment Configuration

Copy the environment template and configure your settings:

cp .env.example .env

Important Configuration Notes:

  • DB_HOST: Use localhost for local development, db-postgres for Docker
  • JWT_SECRET: Generate a secure random string (minimum 32 characters)
  • AWS_S3_*: Configure AWS credentials for file storage

3. Choose Your Development Environment

Option A: Docker Compose (Recommended for Quick Start)

# Start all services
docker-compose up -d

# Check service status
docker-compose ps

# View logs
docker-compose logs -f api

Service Access:

Option B: Local Development Setup

# Start PostgreSQL (ensure it's running locally)
# Update .env with local database settings

# Run database migrations
npm run migration:run

# Seed the database with sample data
npm run seed

# Start the development server
npm run start:dev

πŸ—οΈ Project Architecture & Structure

Directory Overview

catalog-api/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ auth/                 # Authentication & Authorization
β”‚   β”œβ”€β”€ common/               # Shared utilities & decorators
β”‚   β”œβ”€β”€ database/             # Database configuration & migrations
β”‚   β”œβ”€β”€ modules/              # Feature modules
β”‚   β”‚   β”œβ”€β”€ categories/       # Category management
β”‚   β”‚   β”œβ”€β”€ products/         # Product management
β”‚   β”‚   β”œβ”€β”€ files/           # File upload & management
β”‚   β”‚   β”œβ”€β”€ content/         # CMS functionality
β”‚   β”‚   β”œβ”€β”€ tenants/         # Multi-tenant management
β”‚   β”‚   └── users/           # User management
β”‚   β”œβ”€β”€ i18n/                # Internationalization
β”‚   └── main.ts              # Application entry point
β”œβ”€β”€ migrations/               # Database migrations
β”œβ”€β”€ seeds/                   # Database seed files
β”œβ”€β”€ docker/                  # Docker configuration
β”œβ”€β”€ docs/                    # Project documentation
└── test/                    # Test files

Core Modules Structure

Authentication Module (src/auth/)

auth/
β”œβ”€β”€ controllers/             # Auth endpoints
β”œβ”€β”€ services/               # Business logic
β”œβ”€β”€ guards/                 # Route protection
β”œβ”€β”€ strategies/             # JWT & local strategies
└── dto/                    # Data transfer objects

Feature Modules (src/modules/)

modules/
β”œβ”€β”€ [module-name]/
β”‚   β”œβ”€β”€ entities/           # TypeORM entities
β”‚   β”œβ”€β”€ dto/               # Request/response DTOs
β”‚   β”œβ”€β”€ controllers/       # REST endpoints
β”‚   β”œβ”€β”€ services/          # Business logic
β”‚   └── [module].module.ts # Module configuration

Common Utilities (src/common/)

common/
β”œβ”€β”€ decorators/            # Custom decorators
β”œβ”€β”€ filters/              # Exception filters
β”œβ”€β”€ guards/               # Authorization guards
β”œβ”€β”€ interceptors/         # Request/response interceptors
β”œβ”€β”€ pipes/                # Validation pipes
└── utils/                # Helper functions

Database Schema Overview

Core Entities

  • Users & Authentication: users, roles, permissions, refresh_tokens
  • Multi-tenant: tenants, tenant_users, tenant_settings
  • Products: products, categories, product_categories
  • Content: blog_posts, pages, content_blocks
  • Files: files, file_uploads
  • i18n: languages, translations

Translation System

Multi-language support is implemented through dedicated translation tables:

  • categories β†’ categories_translations
  • products β†’ products_translations
  • blog_posts β†’ blog_posts_translations
  • pages β†’ pages_translations

πŸ—„οΈ Database Management

Migration Commands

# Generate a new migration
npm run migration:generate -- -n MigrationName

# Run pending migrations
npm run migration:run

# Revert the last migration
npm run migration:revert

# Show migration status
npm run migration:show

Seeding System

# Run all seeders
npm run seed

# Run specific seeder
npm run seed:specific -- --seed=UserSeeder

# Reset database and reseed
npm run seed:refresh

Database Schema Features

Multi-tenant Data Isolation

-- Every tenant-specific table includes tenant_id
CREATE TABLE products (
    id SERIAL PRIMARY KEY,
    tenant_id INTEGER NOT NULL REFERENCES tenants(id),
    name VARCHAR(255) NOT NULL,
    -- ... other fields
    CONSTRAINT unique_product_per_tenant UNIQUE(tenant_id, id)
);

Translation Support

-- Base entity
CREATE TABLE categories (
    id SERIAL PRIMARY KEY,
    tenant_id INTEGER NOT NULL,
    slug VARCHAR(255) NOT NULL
);

-- Translation table
CREATE TABLE categories_translations (
    id SERIAL PRIMARY KEY,
    category_id INTEGER REFERENCES categories(id),
    language_code VARCHAR(5) NOT NULL,
    name VARCHAR(255) NOT NULL,
    description TEXT
);

Audit Logging

-- All entities include audit fields
CREATE TABLE example_entity (
    id SERIAL PRIMARY KEY,
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW(),
    created_by INTEGER REFERENCES users(id),
    updated_by INTEGER REFERENCES users(id)
);

πŸ”Œ API Documentation & Examples

API Base URL

Key Endpoint Categories

Authentication Endpoints

POST /api/auth/login            # User login
POST /api/auth/register         # User registration
POST /api/auth/refresh          # Refresh access token
POST /api/auth/logout           # User logout
GET  /api/auth/profile          # Get user profile
PUT  /api/auth/profile          # Update user profile

Product Management

GET    /api/products            # List products (with pagination)
POST   /api/products            # Create new product
GET    /api/products/:id        # Get product details
PUT    /api/products/:id        # Update product
DELETE /api/products/:id        # Delete product
GET    /api/products/:id/translations  # Get product translations

Category Management

GET    /api/categories          # List categories (hierarchical)
POST   /api/categories          # Create category
GET    /api/categories/:id      # Get category details
PUT    /api/categories/:id      # Update category
DELETE /api/categories/:id      # Delete category

Content Management

GET    /api/blog-posts          # List blog posts
POST   /api/blog-posts          # Create blog post
GET    /api/blog-posts/:slug    # Get blog post by slug
PUT    /api/blog-posts/:id      # Update blog post
DELETE /api/blog-posts/:id      # Delete blog post

File Upload

POST   /api/files/upload        # Upload single file
POST   /api/files/upload-multiple # Upload multiple files
GET    /api/files/:id           # Get file details
DELETE /api/files/:id           # Delete file

Multi-tenant & Admin

GET    /api/tenants             # List tenants (admin only)
POST   /api/tenants             # Create tenant (admin only)
GET    /api/tenants/:id         # Get tenant details
PUT    /api/tenants/:id         # Update tenant settings

Request/Response Examples

Authentication Request

{
  "email": "user@example.com",
  "password": "securepassword123",
  "tenantSlug": "demo-tenant"
}

Product Creation Request

{
  "name": "Premium Widget",
  "slug": "premium-widget",
  "description": "High-quality widget for professional use",
  "price": 99.99,
  "categoryIds": [1, 2],
  "status": "active",
  "translations": {
    "en": {
      "name": "Premium Widget",
      "description": "High-quality widget for professional use"
    },
    "es": {
      "name": "Widget Premium",
      "description": "Widget de alta calidad para uso profesional"
    }
  }
}

πŸ§ͺ Testing & Quality Assurance

Running Tests

# Run unit tests
npm run test

# Run integration tests
npm run test:e2e

# Run tests with coverage
npm run test:cov

# Run tests in watch mode
npm run test:watch

# Run specific test file
npm run test -- auth.service.spec.ts

Code Quality Tools

# Lint code
npm run lint

# Fix linting issues
npm run lint:fix

# Format code
npm run format

# Type checking
npm run type-check

πŸš€ Deployment Guide

Production Build

# Build the application
npm run build

# Start production server
npm run start:prod

Docker Deployment

# Build production image
docker build -t catalog-api:latest .

# Run with production environment
docker run -d \
  --name catalog-api \
  -p 8000:8000 \
  --env-file .env.production \
  catalog-api:latest

Environment Variables for Production

NODE_ENV=production
PORT=8000
DB_HOST=your-production-db-host
DB_PORT=5432
DB_USERNAME=your-db-user
DB_PASSWORD=your-secure-password
DB_NAME=your-production-db
JWT_SECRET=your-super-secure-jwt-secret
AWS_ACCESS_KEY_ID=your-aws-key
AWS_SECRET_ACCESS_KEY=your-aws-secret
AWS_S3_BUCKET_NAME=your-s3-bucket

πŸ‘₯ Development Workflows

Adding New Features

1. Create a New Module

# Generate module structure
nest generate module modules/new-feature
nest generate controller modules/new-feature
nest generate service modules/new-feature

2. Create Entity and DTOs

// entities/new-feature.entity.ts
@Entity('new_features')
export class NewFeature extends BaseEntity {
  @Column()
  name: string;

  @Column()
  tenantId: number;

  // Add translation support
  @OneToMany(() => NewFeatureTranslation, translation => translation.newFeature)
  translations: NewFeatureTranslation[];
}

3. Generate Migration

npm run migration:generate -- -n CreateNewFeatureTable
npm run migration:run

4. Implement Translation Support

// Add to translation entity
@Entity('new_features_translations')
export class NewFeatureTranslation extends BaseTranslationEntity {
  @ManyToOne(() => NewFeature, feature => feature.translations)
  newFeature: NewFeature;

  @Column()
  name: string;

  @Column('text', { nullable: true })
  description: string;
}

Git Workflow

# Create feature branch
git checkout -b feature/new-feature-name

# Make changes and commit
git add .
git commit -m "feat: add new feature functionality"

# Push and create pull request
git push origin feature/new-feature-name

# After review, merge to main
git checkout main
git pull origin main
git merge feature/new-feature-name

πŸ“‹ Best Practices & Standards

TypeScript Guidelines

  • Use strict TypeScript configurations
  • Implement proper type definitions for all entities
  • Utilize decorators for validation and transformation
  • Follow naming conventions (PascalCase for classes, camelCase for variables)

API Design Principles

  • RESTful resource naming
  • Consistent HTTP status codes
  • Proper error handling and messaging
  • Comprehensive request/response validation
  • OpenAPI documentation for all endpoints

Database Standards

  • Use migrations for schema changes
  • Implement proper indexing strategies
  • Follow naming conventions (snake_case for tables/columns)
  • Ensure data integrity with constraints
  • Implement soft deletes where appropriate

πŸ“š Additional Resources

Documentation Links

Getting Help

Community & Updates


βš™οΈ Advanced Configuration

Hardware Requirements

Minimum Requirements

  • RAM: 4GB minimum, 8GB recommended
  • Storage: 10GB available space
  • CPU: 2 cores minimum, 4+ cores recommended
  • Network: High-speed internet for cloud services

Development Environment

# Install required global packages
npm install -g @nestjs/cli
npm install -g typescript
npm install -g ts-node

# Verify installations
node --version     # Should be 18.0+
npm --version      # Should be latest
nest --version     # Should be 10.0+

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


🀝 Contributing

We welcome contributions! Please see our Contributing Guide for details on:

  • Code of Conduct
  • Development setup
  • Pull request process
  • Coding standards
  • Testing requirements

πŸ™ Acknowledgments

  • NestJS Team - For the incredible framework
  • TypeORM Team - For the robust ORM solution
  • PostgreSQL Community - For the reliable database system
  • Contributors - Thank you to all who have contributed to this project

Built with ❀️ using NestJS, TypeScript, and PostgreSQL

⬆ Back to Top

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages