-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
141 lines (121 loc) · 3.91 KB
/
server.js
File metadata and controls
141 lines (121 loc) · 3.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
// Import services
const database = require('./src/config/database');
const apiRoutes = require('./src/routes/api');
const scheduler = require('./src/services/scheduler');
const app = express();
const PORT = process.env.PORT || 3000;
// Security middleware
app.use(helmet());
// CORS configuration
app.use(cors({
origin: process.env.NODE_ENV === 'production' ? false : true,
credentials: true
}));
// Rate limiting
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
message: 'Too many requests from this IP, please try again later.'
});
app.use(limiter);
// Body parsing middleware
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));
// Routes
app.use('/api', apiRoutes);
// Health check endpoint
app.get('/health', (req, res) => {
res.json({
status: 'OK',
timestamp: new Date().toISOString(),
uptime: process.uptime(),
database: database.isConnected() ? 'Connected' : 'Disconnected'
});
});
// Root endpoint
app.get('/', (req, res) => {
res.json({
message: 'University Email Verifier API',
version: '1.0.0',
endpoints: {
health: '/health',
stats: '/api/stats',
verified: '/api/verified',
generate: '/api/generate',
verify: '/api/verify/start',
scheduler: '/api/scheduler/start'
}
});
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error('Error:', err);
res.status(500).json({
success: false,
error: process.env.NODE_ENV === 'production' ? 'Internal server error' : err.message
});
});
// 404 handler
app.use('*', (req, res) => {
res.status(404).json({
success: false,
error: 'Endpoint not found'
});
});
// Graceful shutdown
process.on('SIGINT', async () => {
console.log('\n🛑 Received SIGINT, shutting down gracefully...');
try {
scheduler.stop();
await database.disconnect();
console.log('✅ Shutdown complete');
process.exit(0);
} catch (error) {
console.error('❌ Error during shutdown:', error);
process.exit(1);
}
});
process.on('SIGTERM', async () => {
console.log('\n🛑 Received SIGTERM, shutting down gracefully...');
try {
scheduler.stop();
await database.disconnect();
console.log('✅ Shutdown complete');
process.exit(0);
} catch (error) {
console.error('❌ Error during shutdown:', error);
process.exit(1);
}
});
// Start server
async function startServer() {
try {
// Connect to database
await database.connect();
// Start the server
app.listen(PORT, () => {
console.log('🚀 University Email Verifier Server Started');
console.log(`📡 Server running on port ${PORT}`);
console.log(`🌐 Environment: ${process.env.NODE_ENV || 'development'}`);
console.log(`📊 Health check: http://localhost:${PORT}/health`);
console.log(`📋 API docs: http://localhost:${PORT}/`);
// Start scheduler if in production or if explicitly enabled
if (process.env.NODE_ENV === 'production' || process.env.AUTO_START_SCHEDULER === 'true') {
console.log('⏰ Starting automated scheduler...');
scheduler.start();
} else {
console.log('⏰ Scheduler not started automatically. Use /api/scheduler/start to start it.');
}
});
} catch (error) {
console.error('❌ Failed to start server:', error);
process.exit(1);
}
}
// Start the server
startServer();