Skip to content

barangezen/medium-be

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

27 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Medium Clone Backend

A robust backend API for a Medium-like blogging platform built with Node.js, Express, Prisma, and PostgreSQL.

Features

  • πŸ” Authentication & Authorization

    • JWT-based authentication with refresh tokens
    • Role-based access control (Admin, Author, Reader)
    • Email verification and password reset
  • πŸ“ Content Management

    • CRUD operations for articles, comments, and tags
    • Draft and published article states
    • Article likes and reading time calculation
  • πŸ” Advanced Search System

    • Global search across articles, users, and tags
    • Advanced filtering and sorting options
    • Search suggestions and autocomplete
    • Trending search terms
    • Search history for authenticated users
    • Full-text search capabilities
  • πŸ‘₯ User Management

    • User profiles with bio and avatar
    • Follow/unfollow system
    • User activity tracking
  • πŸ›‘οΈ Security Features

    • API rate limiting
    • Input validation and sanitization
    • CORS protection
    • Helmet for security headers
  • πŸ“€ File Upload

    • Profile image upload
    • Article cover image upload
    • File type and size validation
  • πŸ“§ Email System

    • Account verification emails
    • Password reset emails
    • Background job processing
  • πŸ”Œ API Features

    • RESTful API design
    • Comprehensive error handling
    • Pagination support
    • API documentation with Swagger

Tech Stack

  • Runtime: Node.js
  • Framework: Express.js
  • Database: PostgreSQL
  • ORM: Prisma
  • Authentication: JWT
  • Validation: Zod
  • File Upload: Multer
  • Email: Nodemailer
  • Testing: Jest + Supertest
  • Documentation: Swagger/OpenAPI

Prerequisites

  • Node.js (v16 or higher)
  • PostgreSQL
  • Redis (for background jobs)

Installation

  1. Clone the repository

    git clone <repository-url>
    cd medium-clone-backend
  2. Install dependencies

    npm install
  3. Environment Setup

    # Copy the environment template
    cp environment-variables.example .env

    IMPORTANT: Fill in ALL required environment variables in .env before starting the application. SECURITY: Never use default passwords. Generate strong, unique passwords for each service.

  4. Database Setup

    # Generate Prisma client
    npm run prisma:generate
    
    # Run database migrations
    npm run prisma:migrate
    
    # (Optional) Seed the database
    npm run prisma:seed
  5. Start the server

    # Development
    npm run dev
    
    # Production
    npm start

Environment Variables

⚠️ SECURITY NOTICE: All environment variables are now required for Docker Compose. No default passwords are provided for security reasons.

Required Variables

# Application Settings
NODE_ENV=development
PORT=3000

# Database Configuration (PostgreSQL) - ALL REQUIRED
POSTGRES_DB=medium_clone_db
POSTGRES_USER=medium_user
POSTGRES_PASSWORD=your_secure_database_password_here
DATABASE_URL="postgresql://username:password@localhost:5432/medium_clone_db"

# Redis Configuration - REQUIRED
REDIS_PASSWORD=your_secure_redis_password_here
REDIS_URL=redis://:your_secure_redis_password_here@localhost:6379

# JWT Configuration - REQUIRED
JWT_SECRET=your_super_secure_jwt_secret_minimum_32_characters
JWT_REFRESH_SECRET=your_super_secure_refresh_secret_minimum_32_characters
JWT_EXPIRES_IN=1d
JWT_REFRESH_EXPIRES_IN=7d

# Email Configuration (SMTP)
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=[email protected]
SMTP_PASS=your_app_password_here
FROM_EMAIL=[email protected]
FROM_NAME=Medium Clone

# Frontend Configuration
FRONTEND_URL=http://localhost:3001

Optional Variables

# File Upload Settings
MAX_FILE_SIZE=5242880

# Rate Limiting
RATE_LIMIT_MAX_REQUESTS=100
RATE_LIMIT_WINDOW_MS=900000

# Security Settings
SECURITY_WEBHOOK_URL=
SECURITY_ALERT_EMAIL=

# Postman API Integration
POSTMAN_API_KEY=
POSTMAN_COLLECTION_ID=
POSTMAN_ENVIRONMENT_ID=

Security Best Practices

  • Use strong, unique passwords for all services
  • JWT secrets must be at least 32 characters long
  • Never commit the .env file to version control
  • Use different credentials for dev/staging/production environments
  • Regularly rotate passwords and secrets

API Endpoints

Authentication

  • POST /api/auth/register - Register new user
  • POST /api/auth/login - User login
  • POST /api/auth/refresh - Refresh access token
  • POST /api/auth/verify-email - Verify email address
  • POST /api/auth/forgot-password - Request password reset
  • POST /api/auth/reset-password - Reset password

Users

  • GET /api/users/profile - Get current user profile
  • PUT /api/users/profile - Update user profile
  • POST /api/users/avatar - Upload avatar
  • GET /api/users/:id - Get user by ID
  • POST /api/users/:id/follow - Follow user
  • DELETE /api/users/:id/follow - Unfollow user

Articles

  • GET /api/articles - Get all articles
  • POST /api/articles - Create new article
  • GET /api/articles/:id - Get article by ID
  • PUT /api/articles/:id - Update article
  • DELETE /api/articles/:id - Delete article
  • POST /api/articles/:id/like - Like article
  • DELETE /api/articles/:id/like - Unlike article

Comments

  • GET /api/articles/:id/comments - Get article comments
  • POST /api/articles/:id/comments - Create comment
  • PUT /api/comments/:id - Update comment
  • DELETE /api/comments/:id - Delete comment

Tags

  • GET /api/tags - Get all tags
  • POST /api/tags - Create new tag
  • GET /api/tags/:slug - Get tag by slug

Search

  • GET /api/search/global - Global search across articles, users, and tags
  • GET /api/search/articles - Advanced article search with filters
  • GET /api/search/users - Search users
  • GET /api/search/tags - Search tags
  • GET /api/search/suggestions - Get search suggestions (autocomplete)
  • GET /api/search/trending - Get trending search terms
  • GET /api/search/history - Get user's search history
  • DELETE /api/search/history - Clear user's search history
  • GET /api/search/fulltext - Full-text search using PostgreSQL

Scripts

npm start          # Start production server
npm run dev        # Start development server with nodemon
npm test           # Run tests
npm run test:watch # Run tests in watch mode
npm run test:coverage # Run tests with coverage report
npm run prisma:generate # Generate Prisma client
npm run prisma:migrate # Run database migrations
npm run prisma:studio # Open Prisma Studio
npm run prisma:seed # Seed database with sample data

# Postman Collection Management
npm run postman:test-connection    # Test Postman API connection
npm run postman:push              # Push both collection and environment to Postman
npm run postman:pull              # Pull both collection and environment from Postman
npm run postman:sync              # Sync files bidirectionally
npm run postman:push-collection   # Push only collection to Postman
npm run postman:pull-collection   # Pull only collection from Postman
npm run postman:push-environment  # Push only environment to Postman
npm run postman:pull-environment  # Pull only environment from Postman

Postman Collection

This project includes automated Postman collection management. The collection includes all API endpoints with proper authentication and test scripts.

Setup

  1. Get your Postman API Key

  2. Get Collection and Environment IDs

    • Collection ID: Found in collection settings or URL
    • Environment ID: Found in environment settings
  3. Add to your .env file

    POSTMAN_API_KEY=PMAK-your-api-key-here
    POSTMAN_COLLECTION_ID=your-collection-id
    POSTMAN_ENVIRONMENT_ID=your-environment-id

Usage

# Test connection
npm run postman:test-connection

# Push local changes to Postman
npm run postman:push

# Pull latest from Postman
npm run postman:pull

# Sync both ways (compares timestamps)
npm run postman:sync

Manual Usage

You can also use the script directly with command line arguments:

node scripts/update-postman.js test-connection --api-key YOUR_KEY --collection-id YOUR_COLLECTION_ID --environment-id YOUR_ENV_ID

Project Structure

src/
β”œβ”€β”€ config/           # Configuration files
β”œβ”€β”€ controllers/      # Route controllers
β”œβ”€β”€ middleware/       # Custom middleware
β”œβ”€β”€ routes/          # API routes
β”œβ”€β”€ services/        # Business logic
β”œβ”€β”€ utils/           # Utility functions
β”œβ”€β”€ validations/     # Zod validation schemas
└── app.js          # Express app setup

prisma/
β”œβ”€β”€ schema.prisma   # Database schema
β”œβ”€β”€ migrations/     # Database migrations
└── seed.js        # Database seeder

tests/              # Test files
uploads/           # File uploads (created at runtime)

Error Handling

The API uses consistent error response format:

{
  "success": false,
  "error": "ERROR_TYPE",
  "message": "Human readable error message",
  "errors": [] // Optional validation errors
}

Common HTTP status codes:

  • 200 - Success
  • 201 - Created
  • 400 - Bad Request
  • 401 - Unauthorized
  • 403 - Forbidden
  • 404 - Not Found
  • 409 - Conflict
  • 429 - Too Many Requests
  • 500 - Internal Server Error

Testing

# Run all tests
npm test

# Run tests in watch mode
npm run test:watch

# Generate coverage report
npm run test:coverage

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Submit a pull request

License

MIT License - see the LICENSE file for details.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages