✨ Características: - 45 ejercicios universitarios (Basic → Advanced) - Renderizado LaTeX profesional - IA generativa (Z.ai/DashScope) - Docker 9 servicios - Tests 123/123 pasando - Seguridad enterprise (JWT, XSS, Rate limiting) 🐳 Infraestructura: - Next.js 14 + Node.js 20 - PostgreSQL 15 + Redis 7 - Docker Compose completo - Nginx + SSL ready 📚 Documentación: - 5 informes técnicos completos - README profesional - Scripts de deployment automatizados Estado: Producción lista ✅
8.4 KiB
8.4 KiB
Math Platform Backend
Backend API for the Linear Algebra Learning Platform built with Node.js, Express, TypeScript, Prisma, and PostgreSQL.
Features
- RESTful API with Express.js
- Type-safe with TypeScript
- ORM with Prisma
- Database with PostgreSQL
- Caching with Redis
- Authentication with JWT
- Rate Limiting with Redis-backed storage
- Structured Logging with Winston
- PDF Processing with pdf-parse and pdf2pic
- AI Integration with MiniMax-M2.5 (Aliyun DashScope)
- Telegram Notifications (backend-only)
- Queue System with Bull
- Docker Support for containerization
Tech Stack
- Runtime: Node.js 20 LTS
- Framework: Express.js 4.x
- Language: TypeScript 5.x
- Database: PostgreSQL 15
- ORM: Prisma 5.x
- Cache/Queue: Redis 7
- Authentication: JWT + bcrypt
- Validation: Zod
- Logging: Winston
- Math Rendering: KaTeX
- AI: MiniMax-M2.5 (OpenAI-compatible)
Project Structure
backend/
├── prisma/
│ └── schema.prisma # Prisma schema with all entities
├── src/
│ ├── config/
│ │ ├── auth/ # Authentication configuration
│ │ ├── database/ # Database configuration
│ │ ├── redis/ # Redis configuration
│ │ └── ai/ # AI service configuration
│ ├── modules/
│ │ ├── auth/ # Authentication module
│ │ ├── pdf/ # PDF processing module
│ │ ├── exercise/ # Exercise management module
│ │ ├── module/ # Module management module
│ │ ├── progress/ # Progress tracking module
│ │ ├── ranking/ # Ranking system module
│ │ ├── notification/ # Notification module
│ │ └── user/ # User management module
│ ├── shared/
│ │ ├── database/ # Prisma client setup
│ │ ├── middleware/ # Express middleware
│ │ ├── utils/ # Utility functions
│ │ └── types/ # TypeScript types
│ ├── workers/ # Background workers
│ └── server.ts # Main server file
├── .env.example # Environment variables template
├── .gitignore
├── package.json
├── tsconfig.json
└── README.md
Database Schema
Core Entities
- User - User accounts with authentication
- Module - 3 pedagogical modules (Fundamentals, Systems/Spaces, Applications)
- Topic - 5 topics (Vectors, Matrices, Systems, Vector Spaces, Linear Programming)
- Exercise - Exercises with LaTeX formulas
- ExerciseAttempt - User exercise attempts
- Progress - User progress per module
- Achievement - Gamification badges/achievements
- UserAchievement - Unlocked achievements
- Ranking - Leaderboard positions (global and per module)
- Notification - Telegram notifications (backend only)
- ProcessedPdf - Processed PDF metadata
Enums
- ModuleType: FUNDAMENTOS, SISTEMAS_ESPACIOS, APLICACIONES
- TopicType: VECTORES, MATRICES, SISTEMAS, ESPACIOS_VECTORIALES, PROGRAMACION_LINEAL
- ExerciseType: MULTIPLE_CHOICE, OPEN_RESPONSE, CALCULATION, PROOF, TRUE_FALSE
- ExerciseDifficulty: BASIC, INTERMEDIATE, ADVANCED, EXPERT
- AttemptStatus: CORRECT, INCORRECT, PARTIAL, PENDING
- AchievementCategory: EXERCISES, MODULES, STREAKS, RANKING, SPECIAL
- AchievementRarity: COMMON, RARE, EPIC, LEGENDARY
Getting Started
Prerequisites
- Node.js 20+ LTS
- PostgreSQL 15
- Redis 7
- Docker (optional, for containerization)
Installation
-
Clone the repository
cd /home/ren/Documents/math2/backend -
Install dependencies
npm install -
Set up environment variables
cp .env.example .env # Edit .env with your configuration -
Set up the database
# Generate Prisma client npm run prisma:generate # Run migrations npm run prisma:migrate # (Optional) Seed database npm run prisma:seed -
Start the development server
npm run dev
The API will be available at http://localhost:3001
API Endpoints
Authentication
POST /api/auth/register- Register new userPOST /api/auth/login- Login userGET /api/auth/me- Get current user profilePOST /api/auth/refresh- Refresh access tokenPOST /api/auth/logout- Logout user
Modules
GET /api/modules- List all modulesGET /api/modules/:id- Get module detailsGET /api/modules/:id/introduction- Get module introductionGET /api/modules/:id/examples- Get module examplesGET /api/modules/:id/exercises- Get module exercisesGET /api/modules/:id/answers- Get module answers
Topics
GET /api/topics- List all topicsGET /api/topics/:id- Get topic detailsGET /api/topics/:id/theory- Get topic theory content
Exercises
GET /api/exercises- List exercisesGET /api/exercises/:id- Get exercise detailsPOST /api/exercises/:id/attempt- Submit exercise attemptGET /api/exercises/:id/solution- Get exercise solution
Progress
GET /api/progress- Get overall progressGET /api/progress/module/:moduleId- Get progress for specific module
Ranking
GET /api/ranking/global- Get global rankingGET /api/ranking/module/:moduleId- Get ranking for specific moduleGET /api/ranking/my-position- Get current user's position
Achievements
GET /api/achievements- List all available achievementsGET /api/achievements/my- Get user's achievements
AI Generation
POST /api/ai/generate-exercise- Generate new exercise with AIPOST /api/ai/validate-answer- Validate answer with AI
Environment Variables
See .env.example for all available environment variables. Key variables include:
DATABASE_URL- PostgreSQL connection stringREDIS_HOST- Redis server hostJWT_SECRET- Secret for JWT signingAI_API_KEY- API key for AI serviceTELEGRAM_BOT_TOKEN- Telegram bot token (backend notifications)
Development Scripts
npm run dev # Start development server with hot reload
npm run build # Build for production
npm start # Start production server
npm run prisma:generate # Generate Prisma client
npm run prisma:migrate # Run database migrations
npm run prisma:studio # Open Prisma Studio
npm test # Run tests
npm run lint # Lint code
npm run format # Format code with Prettier
Docker Usage
# Build image
docker build -t math-backend .
# Run container
docker run -p 3001:3001 --env-file .env math-backend
# Use Docker Compose (from root directory)
docker-compose up backend
API Documentation
API documentation is available using OpenAPI/Swagger. Access it at:
- Production:
http://localhost:3001/api-docs
Testing
# Run all tests
npm test
# Run tests in watch mode
npm run test:watch
# Run tests with coverage
npm run test:coverage
Error Handling
The API uses standard HTTP status codes and returns error responses in the following format:
{
"success": false,
"error": {
"code": "ERROR_CODE",
"message": "Human-readable error message",
"details": {}
},
"meta": {
"timestamp": "2024-01-01T00:00:00.000Z",
"requestId": "req_xxx"
}
}
Logging
Logs are stored in the logs/ directory:
combined.log- All logserror.log- Error logs only
Logs are structured JSON with correlation IDs for request tracing.
Security Features
- JWT-based authentication
- Password hashing with bcrypt
- Rate limiting (Redis-backed)
- CORS configuration
- Helmet.js security headers
- Input validation with Zod
- SQL injection prevention (Prisma)
- XSS protection
Performance Optimization
- Database connection pooling
- Redis caching
- Indexed database queries
- Compression middleware
- Optimized Prisma queries
- Background workers for heavy tasks
Contributing
- Follow the existing code style
- Write tests for new features
- Update documentation
- Use TypeScript for type safety
- Follow git commit conventions
License
MIT
Support
For issues or questions, please create an issue in the repository.