Skip to content

somyaknotfound/youtube-twitter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

YouTube-Twitter Backend

A robust social media backend API built with Node.js, Express.js, and MongoDB. This project combines features from both YouTube and Twitter, allowing users to create content, subscribe to channels, and interact with posts.

πŸš€ Features

User Management

  • User Registration & Authentication with JWT tokens
  • Profile Management with avatar and cover image upload
  • Secure Password Handling with bcrypt encryption
  • Access & Refresh Token implementation for enhanced security

Content Management

  • Tweet Creation with text content
  • Media Upload integration with Cloudinary
  • User Profiles with follower/following statistics
  • Channel Subscriptions system

Advanced Features

  • MongoDB Aggregation Pipelines for complex data queries
  • Subscription Analytics using advanced pipeline operations
  • File Upload Handling with Multer middleware
  • Error Handling with custom error classes
  • Input Validation and sanitization

πŸ› οΈ Tech Stack

Backend Framework

  • Node.js - Runtime environment
  • Express.js - Web application framework
  • MongoDB - NoSQL database
  • Mongoose - MongoDB object modeling

Authentication & Security

  • JWT (JSON Web Tokens) - Authentication tokens
  • bcrypt - Password hashing
  • Cookie Parser - Cookie handling middleware

File Handling

  • Multer - File upload middleware
  • Cloudinary - Cloud-based image/video management

Development Tools

  • Nodemon - Development server auto-restart
  • dotenv - Environment variable management
  • CORS - Cross-origin resource sharing

πŸ“ Project Structure

src/
β”œβ”€β”€ controllers/           # Route handlers
β”‚   └── user.controller.js # User-related operations
β”œβ”€β”€ middlewares/          # Custom middleware
β”‚   β”œβ”€β”€ auth.middleware.js # JWT authentication
β”‚   └── multer.middleware.js # File upload handling
β”œβ”€β”€ models/              # Database schemas
β”‚   β”œβ”€β”€ user.model.js    # User schema
β”‚   β”œβ”€β”€ tweet.model.js   # Tweet schema
β”‚   β”œβ”€β”€ subscription.model.js # Subscription schema
β”‚   β”œβ”€β”€ like.model.js    # Like schema
β”‚   β”œβ”€β”€ comment.model.js # Comment schema
β”‚   β”œβ”€β”€ playlist.model.js # Playlist schema
β”‚   └── video.model.js   # Video schema
β”œβ”€β”€ routes/              # API routes
β”‚   └── user.routes.js   # User-related routes
β”œβ”€β”€ utils/               # Utility functions
β”‚   β”œβ”€β”€ ApiError.js      # Custom error handling
β”‚   β”œβ”€β”€ ApiResponse.js   # Standardized API responses
β”‚   β”œβ”€β”€ asyncHandler.js  # Async error wrapper
β”‚   └── cloudinary.js    # Cloudinary configuration
β”œβ”€β”€ db/                  # Database configuration
β”‚   └── index.js         # MongoDB connection
└── app.js               # Express app configuration

🚦 API Endpoints

Authentication

POST /api/v1/users/register          # User registration
POST /api/v1/users/login             # User login
POST /api/v1/users/logout            # User logout
POST /api/v1/users/refresh-token     # Refresh access token

User Management

GET  /api/v1/users/current-user      # Get current user details
POST /api/v1/users/change-password   # Change user password
PATCH /api/v1/users/update-account   # Update account details
PATCH /api/v1/users/avatar          # Update user avatar
PATCH /api/v1/users/cover-image     # Update cover image
GET  /api/v1/users/c/:username      # Get user channel profile
GET  /api/v1/users/history          # Get watch history

πŸ”§ Installation & Setup

Prerequisites

  • Node.js (v14 or higher)
  • MongoDB (local or Atlas)
  • Cloudinary account for media storage

Installation Steps

  1. Clone the repository

    git clone https://github.com/somyaknotfound/youtube-twitter.git
    cd youtube-twitter
  2. Install dependencies

    npm install
  3. Environment Configuration Create a .env file in the root directory:

    PORT=8000
    MONGODB_URI=mongodb://localhost:27017/youtube-twitter
    CORS_ORIGIN=*
    
    ACCESS_TOKEN_SECRET=your-access-token-secret
    ACCESS_TOKEN_EXPIRY=1d
    REFRESH_TOKEN_SECRET=your-refresh-token-secret  
    REFRESH_TOKEN_EXPIRY=10d
    
    CLOUDINARY_CLOUD_NAME=your-cloudinary-name
    CLOUDINARY_API_KEY=your-cloudinary-api-key
    CLOUDINARY_API_SECRET=your-cloudinary-api-secret
  4. Start the development server

    npm run dev
  5. Access the API

    Server runs on: http://localhost:8000
    Test route: http://localhost:8000/api/v1/users/test
    

πŸ—„οΈ Database Schema

User Model

{
  username: String (unique, lowercase)
  email: String (unique, lowercase)
  fullName: String
  avatar: String (Cloudinary URL)
  coverImage: String (Cloudinary URL)
  watchHistory: [ObjectId] (ref: Video)
  password: String (hashed)
  refreshToken: String
}

Tweet Model

{
  content: String
  owner: ObjectId (ref: User)
  createdAt: Date
  updatedAt: Date
}

Subscription Model

{
  subscriber: ObjectId (ref: User)
  channel: ObjectId (ref: User)
  createdAt: Date
}

πŸ” Advanced MongoDB Features

Aggregation Pipelines

The project extensively uses MongoDB aggregation pipelines for:

  • User Channel Analytics: Complex queries to fetch subscriber counts, subscription status
  • Content Statistics: Advanced data aggregation for user profiles
  • Relationship Mapping: Efficient subscriber-channel relationship queries

Example Pipeline (User Channel Profile)

const channel = await User.aggregate([
  { $match: { username: username.toLowerCase() } },
  {
    $lookup: {
      from: "subscriptions",
      localField: "_id", 
      foreignField: "channel",
      as: "subscribers"
    }
  },
  {
    $lookup: {
      from: "subscriptions",
      localField: "_id",
      foreignField: "subscriber", 
      as: "subscribedTo"
    }
  },
  {
    $addFields: {
      subscribersCount: { $size: "$subscribers" },
      channelSubscribedToCount: { $size: "$subscribedTo" },
      isSubscribed: {
        $cond: {
          if: { $in: [req.user?._id, "$subscribers.subscriber"] },
          then: true,
          else: false
        }
      }
    }
  }
]);

πŸ” Security Features

  • JWT Authentication with access and refresh tokens
  • Password Encryption using bcrypt
  • File Upload Security with Multer configurations
  • Input Validation and sanitization
  • CORS Configuration for cross-origin requests
  • Environment Variables for sensitive data

🚧 Middleware Implementation

Authentication Middleware

  • Verifies JWT tokens from cookies or headers
  • Adds user information to request object
  • Handles token expiration and refresh

File Upload Middleware

  • Handles multipart/form-data requests
  • Integrates with Cloudinary for cloud storage
  • Supports both avatar and cover image uploads

🎯 Key Learning Outcomes

  • MongoDB Aggregation Pipelines for complex data operations
  • JWT Authentication implementation with refresh tokens
  • File Upload handling with cloud storage integration
  • RESTful API design and development
  • Error Handling and middleware pattern implementation
  • Database Modeling for social media applications

🀝 Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

πŸ“„ License

This project is based on the tutorial series from:

Chai aur Code - JavaScript Backend Development

πŸ‘¨β€πŸ’» Author

Somyak - GitHub Profile

πŸ“ž Support

If you have any questions or need help with setup, please open an issue in the GitHub repository.


⭐ Star this repository if you found it helpful!

About

A robust social media backend API built with Node.js, Express.js, and MongoDB. This project combines features from both YouTube and Twitter, allowing users to create content, subscribe to channels, and interact with posts.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors