Skip to content

toluwagbemiga/digital-marketplace-api

Repository files navigation

Digital Marketplace API

A production-grade Laravel API for a digital marketplace where creators can sell digital products (e-books, videos, software, etc.) to customers.

πŸš€ Quick Start

Prerequisites

  • Docker & Docker Compose
  • Git

One-Command Setup

git clone <repository-url>
cd digital-marketplace-api
docker-compose up -d

The application will be available at http://localhost:8000

πŸ“‹ Test Credentials

Creator Account

  • Email: creator@example.com
  • Password: password123
  • Role: Creator (can create and manage products)

Customer Account

  • Email: customer@example.com
  • Password: password123
  • Role: Customer (can purchase and download products)

πŸ—οΈ Architecture Overview

This application follows clean architecture principles with:

Core Layers

  • Controllers: Thin HTTP handlers
  • Services: Business logic encapsulation
  • Models: Data layer with Eloquent ORM
  • Repositories: Data access abstraction
  • Events: Event-driven architecture for decoupled operations

Key Design Patterns

  • SOLID Principles: Single responsibility, dependency injection
  • Repository Pattern: Clean data access layer
  • Service Layer Pattern: Business logic separation
  • Event-Driven Architecture: Asynchronous processing
  • Form Request Validation: Input validation separation

πŸ›‘οΈ Security Implementation

Authentication & Authorization

  • Laravel Sanctum: Token-based API authentication
  • Role-Based Access Control: Creator/Customer role enforcement
  • Middleware Protection: Route-level authorization
  • Policy-Based Authorization: Resource-level permissions

File Security

  • Private File Storage: Files stored outside public directory
  • Temporary Signed URLs: Time-limited download access (30 minutes)
  • Purchase Verification: Download access only for purchased products
  • Creator Access: Product owners can always access their files

Data Protection

  • Environment Variables: No hardcoded secrets
  • Password Hashing: Bcrypt encryption
  • SQL Injection Prevention: Eloquent ORM protection
  • CSRF Protection: Built-in Laravel protection

πŸ—„οΈ Database Design

Core Tables

  • users: User accounts with role-based access
  • categories: Product categorization
  • products: Digital products with metadata
  • purchases: Transaction records with status tracking

Key Features

  • Proper Indexing: Optimized query performance
  • Foreign Key Constraints: Data integrity
  • Soft Deletes: Product recovery capability
  • Unique Constraints: Prevent duplicate purchases

Relationships

User (Creator) -> Products (1:many)
User (Customer) -> Purchases (1:many)
Category -> Products (1:many)
Product -> Purchases (1:many)

πŸ”„ Queue & Background Processing

Implemented Jobs

  • Purchase Notifications: Email notifications via queue
  • File Access Logging: Download activity tracking
  • Event Processing: Asynchronous event handling

Queue Configuration

  • Driver: Redis
  • Horizon: Queue monitoring and management
  • Failed Job Handling: Automatic retry with exponential backoff

πŸ“Š API Documentation

Swagger/OpenAPI

  • Interactive Documentation: Available at /api/documentation
  • Complete Endpoint Coverage: All routes documented
  • Request/Response Examples: Ready-to-test examples
  • Authentication Examples: Token usage demonstrations

Key Endpoints

Authentication

POST /api/register     - User registration
POST /api/login        - User authentication
POST /api/logout       - Token invalidation
GET  /api/me          - Current user profile

Products (Public)

GET /api/products                    - List products (with filtering)
GET /api/products/{id}              - Product details
GET /api/categories                 - List categories

Creator Operations

GET    /api/my-products             - Creator's products
POST   /api/products                - Create product
PUT    /api/products/{id}           - Update product
DELETE /api/products/{id}           - Delete product

Customer Operations

POST /api/purchases                 - Purchase product
GET  /api/library                   - Customer's purchases
GET  /api/products/{id}/download    - Download purchased file

πŸ§ͺ Testing Strategy

Test Coverage

  • Feature Tests: Complete user workflows
  • Unit Tests: Service layer logic
  • Integration Tests: Database interactions
  • Security Tests: Authorization and access control

Test Categories

  • Authentication Flow: Registration, login, logout
  • Product Management: CRUD operations, file handling
  • Purchase Flow: Payment simulation, library access
  • Download Security: Signed URL generation, access control

Running Tests

# Run all tests
docker-compose exec app php artisan test

# Run specific test suite
docker-compose exec app php artisan test --testsuite=Feature

# Run with coverage
docker-compose exec app php artisan test --coverage

πŸš€ Production Deployment

Cloud Platform Deployment (AWS/DigitalOcean/GCP)

Infrastructure Requirements

  • Application Server: EC2/Droplet with PHP 8.2+, Nginx
  • Database: RDS PostgreSQL or managed PostgreSQL
  • Cache/Queue: ElastiCache Redis or managed Redis
  • File Storage: S3 or equivalent object storage
  • Load Balancer: Application Load Balancer for scaling

Environment Setup

# 1. Server provisioning
sudo apt update && sudo apt upgrade -y
sudo apt install nginx php8.2-fpm php8.2-pgsql php8.2-redis composer

# 2. Application deployment
git clone <repository>
composer install --no-dev --optimize-autoloader
php artisan key:generate
php artisan migrate --force
php artisan db:seed --force

# 3. Queue workers
php artisan horizon
# Or: php artisan queue:work --daemon

Storage Configuration

// config/filesystems.php
'private' => [
    'driver' => 's3',
    'key' => env('AWS_ACCESS_KEY_ID'),
    'secret' => env('AWS_SECRET_ACCESS_KEY'),
    'region' => env('AWS_DEFAULT_REGION'),
    'bucket' => env('AWS_BUCKET'),
    'visibility' => 'private',
],

CI/CD Pipeline

GitHub Actions Example

name: Deploy to Production

on:
  push:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: 8.2
      - name: Install dependencies
        run: composer install
      - name: Run tests
        run: php artisan test

  deploy:
    needs: test
    runs-on: ubuntu-latest
    steps:
      - name: Deploy to server
        run: |
          ssh user@server "cd /var/www && git pull"
          ssh user@server "cd /var/www && composer install --no-dev"
          ssh user@server "cd /var/www && php artisan migrate --force"
          ssh user@server "sudo systemctl reload nginx"

Deployment Checklist

  • Environment variables configured
  • Database migrations run
  • Queue workers started
  • File storage permissions set
  • SSL certificates installed
  • Monitoring configured
  • Backup strategy implemented

Queue Workers in Production

# Supervisor configuration for queue workers
[program:horizon]
process_name=%(program_name)s
command=php /var/www/artisan horizon
directory=/var/www
user=www-data
autorestart=true
redirect_stderr=true
stdout_logfile=/var/log/horizon.log

πŸ”§ Development

Local Development Setup

# Install dependencies
composer install
npm install

# Environment setup
cp .env.example .env
php artisan key:generate

# Database setup
php artisan migrate
php artisan db:seed

# Start development server
php artisan serve

Code Quality Tools

# Code formatting
./vendor/bin/pint

# Static analysis
./vendor/bin/phpstan analyse

# Tests
php artisan test

πŸ“ˆ Performance Considerations

Optimization Strategies

  • Database Indexing: Strategic indexes on frequently queried columns
  • Query Optimization: Eager loading to prevent N+1 queries
  • Caching: Redis caching for frequently accessed data
  • File Storage: CDN integration for file delivery
  • Queue Processing: Background job processing for heavy operations

Monitoring

  • Application Performance: Laravel Telescope for debugging
  • Queue Monitoring: Horizon dashboard
  • Error Tracking: Integration with Sentry or similar
  • Database Performance: Query logging and analysis

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Write tests for new functionality
  4. Ensure all tests pass
  5. Submit a pull request

πŸ“„ License

This project is licensed under the MIT License.


Built with Laravel 12, PostgreSQL, Redis, and Docker

About

Production-grade Laravel API for a digital marketplace where creators sell digital products to customers. Features role-based auth, secure file downloads, queue processing, and comprehensive testing.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages