elearning/Backend/.agent/workflowss/e-learning-backend.md
2026-01-08 04:20:49 +00:00

12 KiB

description
Complete workflow for developing E-Learning Platform backend

E-Learning Backend Development Workflow

Complete guide for developing the E-Learning Platform backend from scratch.


🎯 Overview

This workflow covers the entire development process from initial setup to deployment.


Phase 1: Initial Setup

1.1 Environment Setup

Follow the Setup Workflow:

# Clone repository
git clone <repository-url>
cd e-learning/Backend

# Install dependencies
npm install

# Setup environment
cp .env.example .env
# Edit .env with your configuration

# Start Docker services
docker compose up -d

# Run migrations
npx prisma migrate dev

# Seed database
npx prisma db seed

# Start dev server
npm run dev

1.2 Verify Setup

# Test health endpoint
curl http://localhost:4000/health

# Test login
curl -X POST http://localhost:4000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username": "admin", "password": "admin123"}'

Phase 2: Database Design

2.1 Design Schema

Review and update prisma/schema.prisma:

model User {
  id       Int      @id @default(autoincrement())
  username String   @unique
  email    String   @unique
  password String
  role_id  Int
  role     Role     @relation(fields: [role_id], references: [id])
  profile  Profile?
  
  created_at DateTime @default(now())
  updated_at DateTime @updatedAt
}

model Course {
  id              Int      @id @default(autoincrement())
  title           Json     // { th: "", en: "" }
  description     Json
  price           Decimal  @db.Decimal(10, 2)
  is_free         Boolean  @default(false)
  have_certificate Boolean @default(false)
  status          CourseStatus @default(DRAFT)
  
  category_id     Int
  category        Category @relation(fields: [category_id], references: [id])
  
  created_by      Int
  creator         User     @relation(fields: [created_by], references: [id])
  
  chapters        Chapter[]
  instructors     CourseInstructor[]
  
  created_at      DateTime @default(now())
  updated_at      DateTime @updatedAt
  
  @@index([category_id])
  @@index([status])
}

2.2 Create Migration

Follow the Database Migration Workflow:

npx prisma migrate dev --name initial_schema

Phase 3: Core Features Development

3.1 Authentication System

Create endpoints:

  • POST /api/auth/register - User registration
  • POST /api/auth/login - User login
  • POST /api/auth/logout - User logout
  • POST /api/auth/refresh - Refresh token

Implementation steps:

  1. Create src/routes/auth.routes.js
  2. Create src/controllers/auth.controller.js
  3. Create src/services/auth.service.js
  4. Implement JWT middleware
  5. Write tests

Example:

// src/services/auth.service.js
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

class AuthService {
  async register({ username, email, password, role_id = 3 }) {
    const hashedPassword = await bcrypt.hash(password, 10);
    
    const user = await prisma.user.create({
      data: {
        username,
        email,
        password: hashedPassword,
        role_id
      },
      include: { role: true }
    });

    const token = this.generateToken(user);
    return { user, token };
  }

  async login({ username, email, password }) {
    const user = await prisma.user.findFirst({
      where: {
        OR: [
          { username },
          { email }
        ]
      },
      include: { role: true }
    });

    if (!user || !await bcrypt.compare(password, user.password)) {
      throw new Error('Invalid credentials');
    }

    const token = this.generateToken(user);
    return { user, token };
  }

  generateToken(user) {
    return jwt.sign(
      {
        userId: user.id,
        username: user.username,
        role: user.role.code
      },
      process.env.JWT_SECRET,
      { expiresIn: process.env.JWT_EXPIRES_IN }
    );
  }
}

module.exports = new AuthService();

3.2 Course Management

Follow the Create API Endpoint Workflow for:

Instructor endpoints:

  • POST /api/instructor/courses - Create course
  • GET /api/instructor/courses - List my courses
  • PUT /api/instructor/courses/:id - Update course
  • DELETE /api/instructor/courses/:id - Delete course
  • POST /api/instructor/courses/:id/submit - Submit for approval

Public endpoints:

  • GET /api/courses - List approved courses
  • GET /api/courses/:id - Get course details

Student endpoints:

  • POST /api/students/courses/:id/enroll - Enroll in course
  • GET /api/students/courses - My enrolled courses

3.3 Chapters & Lessons

Create endpoints:

  • POST /api/instructor/courses/:courseId/chapters - Create chapter
  • POST /api/instructor/courses/:courseId/chapters/:chapterId/lessons - Create lesson
  • PUT /api/instructor/courses/:courseId/lessons/:lessonId - Update lesson
  • DELETE /api/instructor/courses/:courseId/lessons/:lessonId - Delete lesson

Key features:

  • Multi-language support (th/en)
  • Lesson types (video, text, pdf, quiz)
  • Sequential ordering
  • Prerequisites system

3.4 File Upload System

Follow the File Upload Workflow:

Implement:

  • Video upload for lessons
  • Attachment upload (PDF, DOC, etc.)
  • Image upload for thumbnails
  • S3/MinIO integration
  • File validation (type, size)

Endpoints:

  • POST /api/instructor/lessons/:lessonId/video - Upload video
  • POST /api/instructor/lessons/:lessonId/attachments - Upload attachments
  • GET /api/students/lessons/:lessonId/attachments/:id/download - Download

3.5 Quiz System

Create endpoints:

  • POST /api/instructor/lessons/:lessonId/quiz - Create quiz
  • POST /api/instructor/quizzes/:quizId/questions - Add question
  • GET /api/students/quizzes/:quizId - Get quiz
  • POST /api/students/quizzes/:quizId/submit - Submit quiz

Features:

  • Multiple choice questions
  • Time limits
  • Attempt limits
  • Cooldown periods
  • Score policies (HIGHEST, LATEST, AVERAGE)

3.6 Progress Tracking

Implement:

  • Video progress tracking (save every 5 seconds)
  • Lesson completion
  • Course progress calculation
  • Certificate generation

Endpoints:

  • POST /api/students/lessons/:lessonId/progress - Save progress
  • GET /api/students/lessons/:lessonId/progress - Get progress
  • POST /api/students/lessons/:lessonId/complete - Mark complete
  • GET /api/students/courses/:courseId/certificate - Get certificate

Phase 4: Testing

Follow the Testing Workflow:

4.1 Unit Tests

# Test services
npm test -- unit/auth.service.test.js
npm test -- unit/course.service.test.js

4.2 Integration Tests

# Test API endpoints
npm test -- integration/auth.test.js
npm test -- integration/courses.test.js
npm test -- integration/lessons.test.js

4.3 Coverage

npm test -- --coverage

Target: >80% coverage


Phase 5: Optimization

5.1 Database Optimization

  • Add indexes for frequently queried fields
  • Optimize N+1 queries
  • Use select to limit fields
  • Implement pagination
model Course {
  // ...
  @@index([category_id])
  @@index([status])
  @@index([created_at])
}

5.2 Caching (Redis)

Implement caching for:

  • Course listings
  • User sessions
  • Frequently accessed data
const redis = require('redis');
const client = redis.createClient({
  url: process.env.REDIS_URL
});

// Cache course list
const cacheKey = 'courses:approved';
const cached = await client.get(cacheKey);

if (cached) {
  return JSON.parse(cached);
}

const courses = await prisma.course.findMany(...);
await client.setEx(cacheKey, 3600, JSON.stringify(courses));

5.3 Rate Limiting

const rateLimit = require('express-rate-limit');

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100 // limit each IP to 100 requests per windowMs
});

app.use('/api/', limiter);

Phase 6: Security Hardening

6.1 Security Checklist

  • Input validation on all endpoints
  • SQL injection prevention (Prisma handles this)
  • XSS prevention (sanitize HTML)
  • CSRF protection
  • Rate limiting
  • CORS configuration
  • Helmet.js for security headers
  • File upload validation
  • Strong JWT secrets
  • Password hashing (bcrypt)

6.2 Implement Security Middleware

const helmet = require('helmet');
const cors = require('cors');

app.use(helmet());
app.use(cors({
  origin: process.env.CORS_ORIGIN.split(','),
  credentials: true
}));

Phase 7: Documentation

7.1 API Documentation

Use Swagger/OpenAPI:

const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

7.2 Code Documentation

  • JSDoc comments for all functions
  • README.md with setup instructions
  • API endpoint documentation
  • Database schema documentation

Phase 8: Deployment

Follow the Deployment Workflow:

8.1 Prepare for Production

# Set NODE_ENV
export NODE_ENV=production

# Install production dependencies only
npm ci --production

# Run migrations
npx prisma migrate deploy

# Build (if needed)
npm run build

8.2 Deploy with PM2

pm2 start ecosystem.config.js
pm2 save
pm2 startup

8.3 Setup Nginx

Configure reverse proxy and SSL

8.4 Monitoring

  • Setup PM2 monitoring
  • Configure logging
  • Setup error tracking (Sentry)
  • Health check endpoint

Development Best Practices

1. Code Organization

src/
├── config/          # Configuration files
├── controllers/     # Request handlers
├── middleware/      # Express middleware
├── models/          # Prisma models (generated)
├── routes/          # Route definitions
├── services/        # Business logic
├── utils/           # Utility functions
├── validators/      # Input validation
└── app.js          # Express app setup

2. Git Workflow

# Create feature branch
git checkout -b feature/user-authentication

# Make changes and commit
git add .
git commit -m "feat: implement user authentication"

# Push and create PR
git push origin feature/user-authentication

3. Code Review Checklist

  • Code follows style guide
  • Tests written and passing
  • No console.logs in production code
  • Error handling implemented
  • Input validation added
  • Documentation updated
  • No sensitive data in code

Troubleshooting

Common Issues

Database connection error:

# Check PostgreSQL
docker ps | grep postgres
docker logs elearning-postgres

# Test connection
npx prisma db pull

Port already in use:

# Find process
lsof -i :4000

# Kill process
kill -9 <PID>

Prisma Client error:

# Regenerate client
npx prisma generate

# Reset and migrate
npx prisma migrate reset

Resources


Quick Commands Reference

# Development
npm run dev              # Start dev server
npm test                 # Run tests
npm run lint            # Run linter
npm run format          # Format code

# Database
npx prisma studio       # Open Prisma Studio
npx prisma migrate dev  # Create and apply migration
npx prisma db seed      # Seed database

# Docker
docker compose up -d    # Start services
docker compose down     # Stop services
docker compose logs -f  # View logs

# PM2 (Production)
pm2 start app.js       # Start app
pm2 restart app        # Restart app
pm2 logs              # View logs
pm2 monit             # Monitor resources

Ready to build an amazing E-Learning Platform! 🚀