-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
127 lines (112 loc) · 3.35 KB
/
server.js
File metadata and controls
127 lines (112 loc) · 3.35 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
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
require('dotenv').config();
const { testConnection, initializeDatabase } = require('./config/database');
const schoolRoutes = require('./routes/schoolRoutes');
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(helmet()); // Security headers
app.use(cors()); // Enable CORS
app.use(morgan('combined')); // Logging
app.use(express.json({ limit: '10mb' })); // Parse JSON bodies
app.use(express.urlencoded({ extended: true, limit: '10mb' })); // Parse URL-encoded bodies
// Health check endpoint
app.get('/health', (req, res) => {
res.status(200).json({
success: true,
message: 'School Management API is running',
timestamp: new Date().toISOString(),
environment: process.env.NODE_ENV || 'development'
});
});
// API documentation endpoint
app.get('/', (req, res) => {
res.json({
success: true,
message: 'School Management API',
version: '1.0.0',
endpoints: {
'POST /addSchool': 'Add a new school',
'GET /listSchools': 'Get schools sorted by proximity (requires latitude & longitude query params)',
'GET /school/:id': 'Get a specific school by ID',
'GET /health': 'Health check'
},
documentation: {
addSchool: {
method: 'POST',
url: '/addSchool',
body: {
name: 'string (required)',
address: 'string (required)',
latitude: 'number (required, -90 to 90)',
longitude: 'number (required, -180 to 180)'
}
},
listSchools: {
method: 'GET',
url: '/listSchools?latitude=12.9716&longitude=77.5946',
queryParams: {
latitude: 'number (required, -90 to 90)',
longitude: 'number (required, -180 to 180)'
}
}
}
});
});
// Routes
app.use('/', schoolRoutes);
// 404 handler
app.use('*', (req, res) => {
res.status(404).json({
success: false,
message: 'Endpoint not found',
availableEndpoints: [
'POST /addSchool',
'GET /listSchools',
'GET /school/:id',
'GET /health'
]
});
});
// Global error handler
app.use((error, req, res, next) => {
console.error('Global error handler:', error);
res.status(500).json({
success: false,
message: 'Internal server error',
error: process.env.NODE_ENV === 'development' ? error.message : 'Something went wrong'
});
});
// Initialize database and start server
const startServer = async () => {
try {
// Test database connection
await testConnection();
// Initialize database tables
await initializeDatabase();
// Start server
app.listen(PORT, () => {
console.log(`🚀 Server is running on port ${PORT}`);
console.log(`📚 School Management API is ready!`);
console.log(`🌐 Health check: http://localhost:${PORT}/health`);
console.log(`📖 API docs: http://localhost:${PORT}/`);
});
} catch (error) {
console.error('❌ Failed to start server:', error);
process.exit(1);
}
};
// Handle graceful shutdown
process.on('SIGTERM', () => {
console.log('SIGTERM received, shutting down gracefully');
process.exit(0);
});
process.on('SIGINT', () => {
console.log('SIGINT received, shutting down gracefully');
process.exit(0);
});
// Start the server
startServer();