Skip to content

Wcoder547/js_backend

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

50 Commits
 
 
 
 
 
 
 
 

Repository files navigation

js_backend: YouTube-Style Backend API Clone

A YouTube-style video hosting backend built with Node.js, Express, and MongoDB. This RESTful API implements common features of a video platform (user accounts, video upload, likes, comments, playlists, etc.) as a learning project from the Chai aur Code course. Although there’s no frontend yet, the backend can be run locally and tested with tools like Postman. It includes controllers for users, videos, playlists, comments, likes, tweets (short posts), subscriptions, and a dashboard for stats. The code is organized with clear routes and models, and uses JWT for authentication, Multer for file uploads, and Cloudinary for media storage.

Features

  • User: User registration, login, profile updates and management. Passwords are hashed with bcrypt, and authentication is handled with JSON Web Tokens (JWT).
  • Video: Upload, fetch, update, and delete videos. Videos (and thumbnails) are uploaded via Multer and stored on Cloudinary. Public endpoints allow fetching video lists or details.
  • Likes/Dislikes: Users can like or unlike videos. The backend tracks likes for each video.
  • Comments: Users can add comments to videos. Each comment is linked to a video and author.
  • Playlist: Create and manage video playlists. Users can add or remove videos in their personal playlists.
  • Tweets: (Bonus social feature) Post short “tweets” or micro-posts, and fetch them. This adds a simple social feed on top of video content.
  • Subscriptions: Users can subscribe to other users (channels) and unsubscribe. Fetch a list of subscriptions or subscribers.
  • Dashboard: An endpoint for aggregated stats (e.g., total videos, total users, likes, etc.) or user-specific analytics. Useful for admin or user dashboards.

Tech Stack

  • Node.js & Express: Backend runtime and web framework.

  • MongoDB (Mongoose): NoSQL database for storing users, videos, comments, etc.

  • REST API Architecture: HTTP endpoints returning JSON.

  • Authentication: JSON Web Tokens (JWT) for securing routes (login, protected actions).

  • File Uploads: Multer handles multipart form-data for uploading videos/images.

  • Cloudinary: Cloud service for storing and serving uploaded videos and images.

  • Other Libraries:

    • bcrypt for hashing passwords.
    • cors and cookie-parser for handling cross-origin requests and cookies.
    • dotenv for environment variables.
    • mongoose-aggregate-paginate-v2 for easy pagination of database queries.
    • body-parser (though Express has built-in parsing).
  • Dev Tools:

    • nodemon for live-reloading during development.
    • Prettier for consistent code formatting.

Installation & Setup

  1. Clone the repository to your local machine:

    git clone https://github.com/your-username/js_backend.git
    cd js_backend
  2. Install dependencies:

    npm install
  3. Configure environment variables: Create a .env file in the project root (see below for required keys).

  4. Start the development server:

    npm run dev

    The server will start (e.g., on http://localhost:5000/) and watch for file changes. You can now send requests to the API.

Environment Variables

The project uses a .env file to store sensitive information. Create a .env file with at least the following variables (you can adjust names to match your code):

  • PORT – (Optional) Port number for the server (e.g., 5000).
  • MONGODB_URI – MongoDB connection string (e.g., from MongoDB Atlas or local MongoDB).
  • JWT_SECRET – Secret key for signing JWT access tokens.
  • CLOUDINARY_CLOUD_NAME, CLOUDINARY_API_KEY, CLOUDINARY_API_SECRET – Your Cloudinary credentials for uploading media.

For example, your .env might look like:

PORT=5000
MONGODB_URI=mongodb+srv://username:password@cluster0.mongodb.net/mydatabase
JWT_SECRET=your_jwt_secret_key
CLOUDINARY_CLOUD_NAME=your_cloud_name
CLOUDINARY_API_KEY=your_api_key
CLOUDINARY_API_SECRET=your_api_secret

API Folder/Controller Structure

The project is organized with clear folders for each part of the API:

js_backend/
└── src/
    ├── controllers/      # Logic for handling requests (e.g., userController.js, videoController.js, etc.)
    ├── models/           # Mongoose schemas (e.g., User.js, Video.js, Comment.js, etc.)
    ├── routes/           # Express route handlers mapping URLs to controller functions
    ├── middleware/       # Custom middleware (e.g., auth.js for JWT verification)
    ├── config/           # Configuration files (e.g., database connection, Cloudinary setup)
    └── server.js         # Entry point: initializes Express app, connects to DB, and starts server
  • controllers/: Each file (like videoController.js) exports functions that implement the API operations for that feature.
  • models/: Define the data schemas with Mongoose (e.g., user schema, video schema).
  • routes/: Set up endpoints (e.g., POST /api/videos or GET /api/users) and connect them to the controller logic.
  • middleware/: Functions like authMiddleware check JWT tokens and protect certain routes.
  • config/: Handles external setup like connecting to MongoDB (db.js) and configuring Cloudinary credentials.
  • server.js: Loads environment variables, connects to the database, applies middleware (CORS, JSON parsing, cookie parsing), and starts listening on the specified port.

How to Use the API

You can test the API using Postman or any HTTP client. Below are basic usage examples:

  • Register a new user: POST /api/users/register with JSON body { "name": "Alice", "email": "alice@example.com", "password": "secure123" }.
  • Login (get JWT token): POST /api/users/login with { "email": "...", "password": "..." }. The response contains a JWT.
  • Authenticate requests: Include the JWT in the Authorization header as Bearer <token> for protected routes (like uploading a video).
  • Upload a video: POST /api/videos – Use multipart/form-data with a file field for the video. (Requires auth.) You may also include fields like title and description.
  • List videos: GET /api/videos – Retrieves a list of all videos (public). Optional query params can be used for pagination or searching.
  • Get video details: GET /api/videos/:id – Fetch a single video's data by its ID.
  • Like a video: POST /api/videos/:id/like – Like or unlike the specified video (toggle action). (Requires auth.)
  • Comment on a video: POST /api/videos/:id/comments – Add a comment. Body example: { "text": "Nice video!" }. (Requires auth.)
  • Create a playlist: POST /api/playlists – Create a new playlist. Body example: { "name": "My Favorites", "videoIds": ["id1", "id2"] }. (Requires auth.)
  • Subscribe to a user: POST /api/subscriptions – Subscribe by providing a channel/user ID. (Requires auth.)
  • Post a tweet: POST /api/tweets – Create a short text post. Body example: { "text": "Hello world!" }. (Requires auth.)
  • View dashboard stats: GET /api/dashboard – Retrieve overall statistics (for admin or own profile).

Each endpoint will return JSON responses. Be sure to set the Content-Type header to application/json for JSON requests, and use multipart/form-data for file uploads. Consult the controller and route definitions in the code for more details on request formats and response structures.

Contributing

Contributions are welcome! If you find a bug or have a feature request, please open an issue on GitHub. To contribute code:

  1. Fork the repository.
  2. Create a new branch for your feature or bugfix.
  3. Make your changes, following the existing code style (Prettier is set up for formatting).
  4. Commit and push your branch.
  5. Open a pull request with a description of your changes.

We appreciate any feedback or improvements. This project is meant for learning and growth, so feel free to experiment and refine the code. 🙂

License

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

About

Hey,Everyone from today we are going start our backend joruney

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages