Skip to content

Latest commit

 

History

History
503 lines (364 loc) · 11.5 KB

File metadata and controls

503 lines (364 loc) · 11.5 KB

Nest Logo

E-Learning Backend API built with NestJS framework

📋 Description

The E-Learning Backend is a RESTful API built with NestJS, providing course management, materials, assignments, quizzes, forums, and many other features for an online learning platform.

✨ Features

🔐 Authentication & Authorization

  • Login/Register with JWT (Access Token & Refresh Token)
  • Role-based permissions (Admin, Instructor, Student)
  • CASL-based authorization for specific actions
  • Cookie-based authentication

📚 Course Management

  • Create and manage courses
  • Semester management
  • Course enrollment
  • Study group management
  • Student group assignment

📄 Materials & Assignments

  • Upload and manage learning materials
  • Create and manage assignments
  • Submit assignments with multiple submission support
  • Deadline tracking and late submission handling
  • File attachments for materials and assignments

📝 Questions & Quizzes

  • Question bank management
  • Create quizzes with multiple question types
  • Take quizzes (Quiz Attempts)
  • Automatic grading for multiple-choice questions
  • Time management for quizzes

💬 Forums & Announcements

  • Create and manage forum topics
  • Reply and comment in forums
  • Pin important topics
  • Create announcements for courses
  • File attachments for announcements and forum posts

📧 Email & Notifications

  • Send emails via SMTP
  • Deadline reminders
  • Grade and feedback notifications
  • Queue-based email processing with RabbitMQ

📁 File Management

  • Upload files to Cloudflare R2
  • Manage file attachments for all modules
  • Signed URLs for secure file access
  • Automatic file deletion when resources are deleted

🔔 WebSocket & Real-time

  • WebSocket gateway for real-time communication
  • Real-time notifications
  • Chat and messaging

👥 User Management

  • User information management
  • Avatar upload
  • Profile management

🛠️ Technology Stack

  • Framework: NestJS 11.x
  • Database: PostgreSQL with TypeORM
  • Authentication: JWT (Passport.js)
  • Authorization: CASL
  • File Storage: Cloudflare R2 (S3-compatible)
  • Message Queue: RabbitMQ
  • Email: Nodemailer (SMTP)
  • WebSocket: Socket.IO
  • API Documentation: Swagger/OpenAPI
  • Validation: class-validator, class-transformer
  • Language: TypeScript

📦 Prerequisites

  • Node.js >= 18.x
  • pnpm >= 8.x (or npm/yarn)
  • PostgreSQL >= 12.x
  • RabbitMQ (optional, for email queue)
  • Cloudflare R2 account (for file storage)

🚀 Installation

1. Clone Repository

git clone <repository-url>
cd elearning-backend

2. Install Dependencies

pnpm install

3. Configure Environment Variables

Copy the env.example file to .env:

cp env.example .env

Then edit the .env file with appropriate values (see Environment Variables Configuration section below).

4. Setup Database

Ensure PostgreSQL is running and create the database:

# Connect to PostgreSQL
psql -U postgres

# Create database
CREATE DATABASE "elearning-api";

# Exit
\q

5. Run Migrations (if any)

pnpm run migration:run

6. Seed Sample Data (Optional)

pnpm run seed

After seeding, you can login with:

  • Admin/Instructor: admin / admin
  • Students: student1@example.com / student123

⚙️ Environment Variables Configuration

The .env file contains all necessary environment variables. Refer to env.example for the structure.

Database Configuration

# PostgreSQL Database
DB_HOST=localhost
DB_PORT=5432
DB_USERNAME=postgres
DB_PASSWORD=your_password
DB_NAME=elearning-api

# Or use DATABASE_URL for production
# DATABASE_URL=postgresql://username:password@host:port/database

JWT Configuration

# JWT Secret Key (should use a strong random string)
JWT_SECRET=your-secret-key-here

# Access Token expiration (default: 15 minutes)
JWT_AC_EXPIRES_IN=15m

# Refresh Token expiration (default: 7 days)
JWT_RF_EXPIRES_IN=7d

Email Configuration (SMTP)

# SMTP Server
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_SECURE=false

# SMTP Credentials
SMTP_USER=your-email@gmail.com
SMTP_PASS=your-app-password

# Email From
SMTP_FROM=your-email@gmail.com
SMTP_FROM_NAME=TDTU-elearning

Note: If using Gmail, you need to create an App Password instead of your regular password.

RabbitMQ Configuration

# RabbitMQ Connection URL
RABBITMQ_URL=amqp://localhost:5672

# Or with authentication
# RABBITMQ_URL=amqp://username:password@localhost:5672

Cloudflare R2 Configuration

# R2 Endpoint (from Cloudflare Dashboard)
CLOUDFLARE_R2_ENDPOINT=https://your-account-id.r2.cloudflarestorage.com

# R2 Credentials
CLOUDFLARE_R2_ACCESS_KEY=your-access-key-id
CLOUDFLARE_R2_SECRET_KEY=your-secret-access-key

# R2 Bucket Name
CLOUDFLARE_R2_BUCKET_NAME=your-bucket-name

# Public Domain (if using custom domain)
CLOUDFLARE_R2_PUBLIC_DOMAIN=https://cdn.yourdomain.com

# Or Worker URL (if using Cloudflare Worker)
CLOUDFLARE_WORKER_URL=https://your-worker.workers.dev

Server Configuration

# Server Port (default: 3000)
PORT=3000

# Server Host (default: 0.0.0.0)
HOST=0.0.0.0

# Node Environment
NODE_ENV=development

Production Configuration

For production, you can use DATABASE_URL instead of individual variables:

DATABASE_URL=postgresql://username:password@host:port/database?sslmode=require
NODE_ENV=production

🏃 Running the Application

Development Mode

pnpm run start:dev

The application will run at http://localhost:3000 (or the port configured in .env).

Production Mode

# Build the application
pnpm run build

# Run production
pnpm run start:prod

Debug Mode

pnpm run start:debug

📚 API Documentation

After running the application, access Swagger UI at:

http://localhost:3000/api

Swagger UI provides:

  • List of all endpoints
  • Request/response schemas
  • Test API directly from browser
  • Authentication with Bearer Token

Additional Documentation

🧪 Testing

Unit Tests

pnpm run test

E2E Tests

pnpm run test:e2e

Test Coverage

pnpm run test:cov

Test Scripts

The script-test/ directory contains API test scripts. See the README in that directory for usage instructions.

📁 Project Structure

src/
├── announcements/      # Announcement management
├── assignments/       # Assignment management
├── auth/              # Authentication and authorization
├── casl/             # CASL authorization policies
├── courses/           # Course management
├── emails/            # Email service
├── enrollments/       # Course enrollment
├── files/             # File management (R2)
├── forums/            # Forums
├── groups/            # Group management
├── materials/         # Learning materials
├── messages/          # Messages
├── notifications/     # Notifications
├── question-banks/    # Question banks
├── quizzes/           # Quizzes
├── rabbitmq/          # RabbitMQ service
├── refresh-tokens/    # Refresh token management
├── seed/              # Database seeding
├── semesters/         # Semester management
├── submissions/       # Assignment submissions
├── users/             # User management
├── websocket/         # WebSocket gateway
├── app.module.ts      # Root module
└── main.ts            # Application entry point

🔧 Database Migrations

Create Migration

pnpm run migration:generate -- -n MigrationName

Run Migrations

pnpm run migration:run

Revert Migration

pnpm run migration:revert

Create Empty Migration

pnpm run migration:create -- -n MigrationName

🌱 Database Seeding

Seed Data

pnpm run seed

Clear Existing Data

pnpm run seed clear

See Seed README for more details about seeded data.

🚢 Deployment

Production Checklist

  1. ✅ Configure environment variables for production
  2. ✅ Ensure NODE_ENV=production
  3. ✅ Use DATABASE_URL for database connection
  4. ✅ Configure SSL for database (if needed)
  5. ✅ Configure CORS for production domain
  6. ✅ Build application: pnpm run build
  7. ✅ Run migrations: pnpm run migration:run
  8. ✅ Configure reverse proxy (Nginx) if needed
  9. ✅ Configure process manager (PM2) for Node.js

Deployment Scripts

See deploy.sh file for automated deployment script.

VPS Setup

See the following documents for VPS setup instructions:

🔒 Security

  • JWT tokens with expiration
  • Refresh token rotation
  • Password hashing with bcrypt
  • CASL-based authorization
  • CORS configuration
  • Input validation with class-validator
  • SQL injection protection (TypeORM)

📝 Available Scripts

# Development
pnpm run start:dev      # Run development mode with hot-reload
pnpm run start:debug    # Run debug mode

# Production
pnpm run build          # Build application
pnpm run start:prod     # Run production mode

# Testing
pnpm run test           # Run unit tests
pnpm run test:e2e       # Run e2e tests
pnpm run test:cov       # Test coverage

# Database
pnpm run migration:run      # Run migrations
pnpm run migration:generate # Generate new migration
pnpm run migration:revert   # Revert migration
pnpm run seed               # Seed data

# Code Quality
pnpm run lint           # Lint code
pnpm run format         # Format code with Prettier

🐛 Troubleshooting

Database Connection Errors

  • Check PostgreSQL is running: pg_isready
  • Check credentials in .env
  • Check firewall and network settings

File Upload Errors

  • Check Cloudflare R2 credentials configuration
  • Check bucket permissions
  • Check network connectivity to R2 endpoint

Email Errors

  • Check SMTP credentials
  • For Gmail, use App Password
  • Check firewall is not blocking port 587/465

RabbitMQ Errors

  • Check RabbitMQ is running: rabbitmqctl status
  • Check connection URL in .env
  • Check permissions and virtual host

📞 Support

If you encounter issues, please:

  1. Check the documentation in the root directory
  2. View application logs
  3. Check Swagger UI at /api endpoint
  4. Contact the development team

📄 License

MIT licensed

🙏 Resources


Last Updated: 2025-12-5
Version: 1.0.0