elearning/.agent/workflows/e-learning-backend.md

460 lines
10 KiB
Markdown
Raw Normal View History

---
description: Complete workflow for developing E-Learning Platform backend
---
# E-Learning Backend Development Workflow
Complete guide for developing the E-Learning Platform backend using TypeScript and TSOA.
---
## 🎯 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](./setup.md):
```bash
# Clone repository
git clone <repository-url>
cd e-learning/Backend
# Install dependencies
npm install
# Install TypeScript and TSOA
npm install -D typescript @types/node @types/express ts-node nodemon
npm install tsoa swagger-ui-express
# 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
```bash
# 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`:
```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](./database-migration.md):
```bash
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 TSOA controller with `@Route`, `@Post` decorators
2. Create TypeScript service with interfaces
3. Implement JWT middleware
4. Write tests
See [Create API Endpoint Workflow](./create-api-endpoint.md) for detailed examples.
### 3.2 Course Management
Follow the [Create API Endpoint Workflow](./create-api-endpoint.md) 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](./file-upload.md):
**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](./testing.md):
### 4.1 Unit Tests
```bash
# Test services
npm test -- unit/auth.service.test.js
npm test -- unit/course.service.test.js
```
### 4.2 Integration Tests
```bash
# Test API endpoints
npm test -- integration/auth.test.js
npm test -- integration/courses.test.js
npm test -- integration/lessons.test.js
```
### 4.3 Coverage
```bash
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
```prisma
model Course {
// ...
@@index([category_id])
@@index([status])
@@index([created_at])
}
```
### 5.2 Rate Limiting
Use `express-rate-limit` middleware to limit requests (e.g., 100 requests per 15 minutes).
---
## 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
Use `helmet()` for security headers and configure CORS with allowed origins.
---
## Phase 7: Documentation
### 7.1 API Documentation
TSOA automatically generates Swagger/OpenAPI documentation:
```typescript
import swaggerUi from 'swagger-ui-express';
app.use('/api-docs', swaggerUi.serve, async (_req, res) => {
return res.send(
swaggerUi.generateHTML(await import('../public/swagger.json'))
);
});
```
**Generate documentation:**
```bash
npm run tsoa:gen
```
Access at: `http://localhost:4000/api-docs`
### 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](./deployment.md):
### 8.1 Prepare for Production
```bash
# 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
```bash
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
```bash
# 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
- **Database error**: Check `docker logs elearning-postgres`, run `npx prisma db pull`
- **Port in use**: Find with `lsof -i :4000`, kill with `kill -9 <PID>`
- **Prisma error**: Run `npx prisma generate` or `npx prisma migrate reset`
---
## Resources
- [Backend Development Rules](../rules/rules.md)
- [Agent Skills Backend](../../agent_skills_backend.md)
- [API Documentation](../../docs/api-docs/)
- [Development Setup](../../docs/development_setup.md)
---
## Quick Commands Reference
```bash
# Development
npm run dev # Start dev server (ts-node)
npm run build # Build TypeScript
npm run tsoa:gen # Generate TSOA routes & Swagger
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! 🚀**