add changes
This commit is contained in:
140
backend/server.js
Normal file
140
backend/server.js
Normal file
@@ -0,0 +1,140 @@
|
||||
require('dotenv').config();
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
const helmet = require('helmet');
|
||||
const morgan = require('morgan');
|
||||
const rateLimit = require('express-rate-limit');
|
||||
const { testConnection, getDatabaseStats } = require('./config/db');
|
||||
const { validateEnvironment } = require('./validate-env');
|
||||
|
||||
// Validate environment configuration on startup
|
||||
console.log('\n🔧 Validating environment configuration...');
|
||||
const isEnvValid = validateEnvironment();
|
||||
if (!isEnvValid) {
|
||||
console.error('❌ Environment validation failed. Please fix errors and restart.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const app = express();
|
||||
|
||||
// Configuration
|
||||
const config = require('./config/config');
|
||||
const PORT = config.server.port;
|
||||
const API_PREFIX = config.server.apiPrefix;
|
||||
const NODE_ENV = config.server.nodeEnv;
|
||||
|
||||
// Security middleware
|
||||
app.use(helmet());
|
||||
|
||||
// CORS configuration
|
||||
app.use(cors(config.cors));
|
||||
|
||||
// Body parser middleware
|
||||
app.use(express.json({ limit: '10mb' }));
|
||||
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
|
||||
|
||||
// Logging middleware
|
||||
if (NODE_ENV === 'development') {
|
||||
app.use(morgan('dev'));
|
||||
} else {
|
||||
app.use(morgan('combined'));
|
||||
}
|
||||
|
||||
// Rate limiting
|
||||
const limiter = rateLimit({
|
||||
windowMs: config.rateLimit.windowMs,
|
||||
max: config.rateLimit.maxRequests,
|
||||
message: config.rateLimit.message,
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
});
|
||||
|
||||
app.use(API_PREFIX, limiter);
|
||||
|
||||
// Health check endpoint
|
||||
app.get('/health', async (req, res) => {
|
||||
const dbStats = await getDatabaseStats();
|
||||
|
||||
res.status(200).json({
|
||||
status: 'OK',
|
||||
message: 'Interview Quiz API is running',
|
||||
timestamp: new Date().toISOString(),
|
||||
environment: NODE_ENV,
|
||||
database: dbStats
|
||||
});
|
||||
});
|
||||
|
||||
// API routes
|
||||
const authRoutes = require('./routes/auth.routes');
|
||||
const guestRoutes = require('./routes/guest.routes');
|
||||
const categoryRoutes = require('./routes/category.routes');
|
||||
const questionRoutes = require('./routes/question.routes');
|
||||
const adminRoutes = require('./routes/admin.routes');
|
||||
|
||||
app.use(`${API_PREFIX}/auth`, authRoutes);
|
||||
app.use(`${API_PREFIX}/guest`, guestRoutes);
|
||||
app.use(`${API_PREFIX}/categories`, categoryRoutes);
|
||||
app.use(`${API_PREFIX}/questions`, questionRoutes);
|
||||
app.use(`${API_PREFIX}/admin`, adminRoutes);
|
||||
|
||||
// Root endpoint
|
||||
app.get('/', (req, res) => {
|
||||
res.json({
|
||||
message: 'Welcome to Interview Quiz API',
|
||||
version: '2.0.0',
|
||||
documentation: '/api-docs'
|
||||
});
|
||||
});
|
||||
|
||||
// 404 handler
|
||||
app.use((req, res, next) => {
|
||||
res.status(404).json({
|
||||
success: false,
|
||||
message: 'Route not found',
|
||||
path: req.originalUrl
|
||||
});
|
||||
});
|
||||
|
||||
// Global error handler
|
||||
app.use((err, req, res, next) => {
|
||||
console.error('Error:', err);
|
||||
|
||||
const statusCode = err.statusCode || 500;
|
||||
const message = err.message || 'Internal Server Error';
|
||||
|
||||
res.status(statusCode).json({
|
||||
success: false,
|
||||
message: message,
|
||||
...(NODE_ENV === 'development' && { stack: err.stack })
|
||||
});
|
||||
});
|
||||
|
||||
// Start server
|
||||
app.listen(PORT, async () => {
|
||||
console.log(`
|
||||
╔════════════════════════════════════════╗
|
||||
║ Interview Quiz API - MySQL Edition ║
|
||||
╚════════════════════════════════════════╝
|
||||
|
||||
🚀 Server running on port ${PORT}
|
||||
🌍 Environment: ${NODE_ENV}
|
||||
🔗 API Endpoint: http://localhost:${PORT}${API_PREFIX}
|
||||
📊 Health Check: http://localhost:${PORT}/health
|
||||
`);
|
||||
|
||||
// Test database connection on startup
|
||||
console.log('🔌 Testing database connection...');
|
||||
const connected = await testConnection();
|
||||
if (!connected) {
|
||||
console.warn('⚠️ Warning: Database connection failed. Server is running but database operations will fail.');
|
||||
}
|
||||
});
|
||||
|
||||
// Handle unhandled promise rejections
|
||||
process.on('unhandledRejection', (err) => {
|
||||
console.error('Unhandled Promise Rejection:', err);
|
||||
// Close server & exit process
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
module.exports = app;
|
||||
Reference in New Issue
Block a user