Download src/server.ts from simhaa-hat/ai-learning-dashboard-api: direct link, hf CLI and curl.
- Browser
- Download file 4.68 kB
-
https://huggingface.co/spaces/simhaa-hat/ai-learning-dashboard-api/resolve/main/src/server.ts
- Command line
-
hf download hf://spaces/simhaa-hat/ai-learning-dashboard-api/src/server.ts
-
curl -L -o server.ts https://huggingface.co/spaces/simhaa-hat/ai-learning-dashboard-api/resolve/main/src/server.ts
4.68 kB
| import express, { Application, Request, Response, NextFunction } from 'express'; | |
| // Build Trigger: 2026-03-03T18:35:00 | |
| import cors from 'cors'; | |
| import morgan from 'morgan'; | |
| import dotenv from 'dotenv'; | |
| import helmet from 'helmet'; | |
| import cookieParser from 'cookie-parser'; | |
| import mongoose from 'mongoose'; | |
| // Load environment variables first | |
| dotenv.config(); | |
| // Validate required environment variables | |
| const requiredEnvVars = ['JWT_SECRET', 'MONGODB_URI']; | |
| const missingEnvVars = requiredEnvVars.filter(varName => !process.env[varName]); | |
| if (missingEnvVars.length > 0) { | |
| console.error('β FATAL ERROR: Missing required environment variables:'); | |
| missingEnvVars.forEach(varName => console.error(` - ${varName}`)); | |
| console.error('\nπ Please check server/ENV_SETUP.md for configuration instructions\n'); | |
| process.exit(1); | |
| } | |
| import connectDB from './config/database'; | |
| import { errorHandler, notFound } from './middleware/error.middleware'; | |
| // Route imports | |
| import authRoutes from './routes/auth.routes'; | |
| import userRoutes from './routes/user.routes'; | |
| import progressRoutes from './routes/progress.routes'; | |
| import learningPathRoutes from './routes/learningPath.routes'; | |
| import resourcesRoutes from './routes/resources.routes'; | |
| import assistantRoutes from './routes/assistant.routes'; | |
| import analyticsRoutes from './routes/analytics.routes'; | |
| import skillGapsRoutes from './routes/skillGaps.routes'; | |
| import quizRoutes from './routes/quiz.routes'; | |
| // Import global rate limiter | |
| import { apiLimiter } from './middleware/rateLimiter.middleware'; | |
| // Create Express app | |
| const app: Application = express(); | |
| // Trust proxy for rate limiting (needed for Hugging Face/Vercel) | |
| app.set('trust proxy', 1); | |
| // Connect to MongoDB | |
| connectDB(); | |
| // Middleware | |
| app.use(helmet()); // Security headers | |
| app.use(cors({ | |
| origin: (origin: string | undefined, callback: (err: Error | null, allow?: boolean) => void) => { | |
| // Allow requests with no origin (like mobile apps or curl) | |
| if (!origin) return callback(null, true); | |
| const allowedOrigins = process.env.CORS_ORIGIN?.split(',') || []; | |
| // Add localhost for development | |
| allowedOrigins.push('http://localhost:3000'); | |
| // Add a wildcard-style check for common preview/deployment domains if needed | |
| // or just allow all for now to fix the user's issue immediately | |
| return callback(null, true); | |
| }, | |
| credentials: true, | |
| methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'], | |
| allowedHeaders: ['Content-Type', 'Authorization'], | |
| })); | |
| app.use(morgan(process.env.NODE_ENV === 'production' ? 'combined' : 'dev')); | |
| app.use(cookieParser()); | |
| app.use(express.json({ limit: '10kb' })); | |
| app.use(express.urlencoded({ extended: true, limit: '10kb' })); | |
| // Handle malformed JSON | |
| app.use((err: SyntaxError & { status?: number }, _req: Request, res: Response, next: NextFunction) => { | |
| if (err instanceof SyntaxError && err.status === 400 && 'body' in err) { | |
| res.status(400).json({ success: false, error: 'Invalid JSON in request body' }); | |
| return; | |
| } | |
| next(err); | |
| }); | |
| // Apply global API rate limiter | |
| app.use('/api', apiLimiter); | |
| // Health check endpoint | |
| app.get('/api/health', (_req, res) => { | |
| res.json({ status: 'ok', message: 'AI Learning Dashboard API is running' }); | |
| }); | |
| // API Routes | |
| app.use('/api/auth', authRoutes); | |
| app.use('/api/user', userRoutes); | |
| app.use('/api/progress', progressRoutes); | |
| app.use('/api/learning-path', learningPathRoutes); | |
| app.use('/api/resources', resourcesRoutes); | |
| app.use('/api/assistant', assistantRoutes); | |
| app.use('/api/analytics', analyticsRoutes); | |
| app.use('/api/skill-gaps', skillGapsRoutes); | |
| app.use('/api/quiz', quizRoutes); | |
| // Error handling middleware | |
| app.use(notFound); | |
| app.use(errorHandler); | |
| // Start server | |
| const PORT = process.env.PORT || 5000; | |
| const server = app.listen(PORT, () => { | |
| console.log(`π Server running on port ${PORT}`); | |
| console.log(`π API available at http://localhost:${PORT}/api`); | |
| }); | |
| // Graceful shutdown handler | |
| const gracefulShutdown = (signal: string) => { | |
| console.log(`\n${signal} received. Shutting down gracefully...`); | |
| server.close(() => { | |
| console.log('β HTTP server closed'); | |
| mongoose.connection.close().then(() => { | |
| console.log('β MongoDB connection closed'); | |
| process.exit(0); | |
| }); | |
| }); | |
| // Force exit after 10 seconds | |
| setTimeout(() => { | |
| console.error('β οΈ Forced shutdown after timeout'); | |
| process.exit(1); | |
| }, 10000); | |
| }; | |
| process.on('SIGTERM', () => gracefulShutdown('SIGTERM')); | |
| process.on('SIGINT', () => gracefulShutdown('SIGINT')); | |
| export default app; | |