-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
323 lines (283 loc) Β· 9.86 KB
/
Copy pathserver.ts
File metadata and controls
323 lines (283 loc) Β· 9.86 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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
const express = require('express');
const testRoute = require('./routes/testRoutes');
const apiRoutes = require('./routes/api');
const { testConnection } = require('./utils/db');
const { specs, swaggerUi } = require('./config/swagger');
const cors = require('cors');
// Load environment variables from .env file
require('dotenv').config();
// Import types for TypeScript
import { Request, Response, NextFunction } from 'express';
// Enhanced logging function
const log = (level: string, message: string, data?: any) => {
const timestamp = new Date().toISOString();
console.log(`[${timestamp}] [${level.toUpperCase()}] ${message}`);
if (data) {
console.log(JSON.stringify(data, null, 2));
}
};
// Log startup information
log('info', 'π Starting Buddies Inn Backend Server...');
log('info', `Environment: ${process.env.NODE_ENV || 'development'}`);
log('info', `Port: ${process.env.PORT || 3000}`);
log('info', `Database URL configured: ${!!process.env.DATABASE_URL}`);
log('info', `JWT Secret configured: ${!!process.env.JWT_SECRET}`);
const app = express();
// Middleware to parse incoming JSON requests
app.use(cors());
app.use(express.json());
log('info', 'β
Express middleware configured');
// Request logging middleware
app.use((req: Request, res: Response, next: NextFunction) => {
log('info', `π₯ ${req.method} ${req.path}`, {
ip: req.ip,
userAgent: req.get('User-Agent'),
query: req.query,
headers: Object.keys(req.headers)
});
next();
});
// Error catching middleware for route handlers
const asyncHandler = (fn: Function) => (req: Request, res: Response, next: NextFunction) => {
Promise.resolve(fn(req, res, next)).catch((error: Error) => {
log('error', `Async handler error in ${req.method} ${req.path}:`, {
message: error.message,
stack: error.stack
});
next(error);
});
};
// Swagger documentation with error handling
try {
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs, {
explorer: true,
customCss: '.swagger-ui .topbar { display: none }',
customSiteTitle: 'Buddies Inn API Documentation',
}));
log('info', 'π Swagger documentation configured at /api-docs');
} catch (error) {
log('error', 'Failed to configure Swagger documentation:', error);
}
// Root route - basic server status message
app.get('/', asyncHandler((req: Request, res: Response) => {
const serverInfo = {
message: 'π Buddies Inn Backend server is running!',
environment: process.env.NODE_ENV || 'development',
timestamp: new Date().toISOString(),
version: '1.0.0',
endpoints: {
health: '/api/health',
docs: '/api-docs',
api: '/api'
}
};
log('info', 'π Root endpoint accessed');
res.json(serverInfo);
}));
// Debug endpoint to check environment variables (without exposing secrets)
app.get('/debug', asyncHandler((req: Request, res: Response) => {
const debugInfo = {
timestamp: new Date().toISOString(),
environment: process.env.NODE_ENV || 'development',
port: process.env.PORT || 3000,
hasDatabase: !!process.env.DATABASE_URL,
hasJwtSecret: !!process.env.JWT_SECRET,
nodeVersion: process.version,
platform: process.platform,
uptime: process.uptime(),
memory: process.memoryUsage()
};
log('info', 'π Debug endpoint accessed', debugInfo);
res.json(debugInfo);
}));
// Mount test routes under /api/test with error handling
try {
app.use('/api/test', testRoute);
log('info', 'π§ͺ Test routes mounted at /api/test');
} catch (error) {
log('error', 'Failed to mount test routes:', error);
}
// Mount API routes under /api with error handling
try {
app.use('/api', apiRoutes);
log('info', 'π API routes mounted at /api');
} catch (error) {
log('error', 'Failed to mount API routes:', error);
}
// Simple health check that doesn't require database
app.get('/health-simple', (req: Request, res: Response) => {
res.status(200).json({
status: 'ok',
message: 'Server is running',
timestamp: new Date().toISOString(),
environment: process.env.NODE_ENV || 'development'
});
});
// Enhanced health check route for monitoring server status
app.get('/api/health', asyncHandler(async (req: Request, res: Response) => {
const startTime = Date.now();
try {
// Test database connection with timeout
const dbStatus = await Promise.race([
testConnection(),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Database timeout')), 5000)
)
]) as boolean;
const responseTime = Date.now() - startTime;
const healthInfo = {
status: 'ok',
message: 'Health check passed',
timestamp: new Date().toISOString(),
uptime: `${Math.floor(process.uptime())}s`,
responseTime: `${responseTime}ms`,
database: {
connected: dbStatus,
url: process.env.DATABASE_URL ? 'configured' : 'missing'
},
environment: {
nodeEnv: process.env.NODE_ENV || 'development',
port: process.env.PORT || 3000,
jwtSecret: process.env.JWT_SECRET ? 'configured' : 'missing'
},
memory: process.memoryUsage(),
version: process.version
};
log('info', 'π Health check completed', {
dbConnected: dbStatus,
responseTime: `${responseTime}ms`
});
res.status(200).json(healthInfo);
} catch (error) {
log('error', 'Health check failed:', error);
res.status(500).json({
status: 'error',
message: 'Health check failed',
timestamp: new Date().toISOString(),
error: error instanceof Error ? error.message : 'Unknown error'
});
}
}));
// 404 handler - catches all unknown routes
app.use((req: Request, res: Response, next: NextFunction) => {
log('warn', `π 404 - Route not found: ${req.method} ${req.originalUrl}`, {
ip: req.ip,
userAgent: req.get('User-Agent')
});
res.status(404).json({
error: 'Not Found',
message: `Route ${req.originalUrl} does not exist`,
timestamp: new Date().toISOString(),
availableEndpoints: [
'/',
'/debug',
'/api/health',
'/api-docs',
'/api/test',
'/api'
]
});
});
// Global error handler - handles invalid JSON and other errors
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
log('error', `π₯ Global error handler triggered for ${req.method} ${req.path}:`, {
message: err.message,
stack: err.stack,
code: err.code,
status: err.status
});
if (err instanceof SyntaxError && (err as any).status === 400 && 'body' in err) {
// Handle invalid JSON error
return res.status(400).json({
error: 'Invalid JSON',
message: 'Request body contains invalid JSON',
timestamp: new Date().toISOString()
});
}
// Handle database connection errors
if (err.code === 'P1001' || err.code === 'P1008') {
return res.status(503).json({
error: 'Database Connection Error',
message: 'Unable to connect to the database',
timestamp: new Date().toISOString()
});
}
// Log error stack and send generic error response
return res.status(err.status || 500).json({
error: 'Internal Server Error',
message: process.env.NODE_ENV === 'development' ? err.message : 'Something went wrong',
timestamp: new Date().toISOString(),
...(process.env.NODE_ENV === 'development' && { stack: err.stack })
});
});
// Set server port from environment or default to 3000
const PORT = process.env.PORT || 3000;
// Initialize database connection and start server
const startServer = async () => {
try {
log('info', 'π Attempting database connection...');
// Test database connection with timeout for serverless
let dbConnected = false;
try {
dbConnected = await Promise.race([
testConnection(),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Database connection timeout')), 10000)
)
]) as boolean;
} catch (dbError) {
log('warn', 'β οΈ Database connection failed, but starting server anyway:', dbError);
// Don't exit in serverless environment - let server start without DB
dbConnected = false;
}
if (dbConnected) {
log('info', 'β
Database connection successful');
} else {
log('warn', 'β οΈ Starting server without database connection');
}
// Start the server and listen on the specified port
const server = app.listen(PORT, () => {
log('info', `π Server listening on port ${PORT}`);
log('info', `π Server URL: http://localhost:${PORT}`);
log('info', `π Health check: http://localhost:${PORT}/api/health`);
log('info', `π Debug info: http://localhost:${PORT}/debug`);
log('info', `π API Documentation: http://localhost:${PORT}/api-docs`);
log('info', 'β¨ Server startup completed successfully');
});
// Handle server errors
server.on('error', (error: Error) => {
log('error', 'π₯ Server error:', error);
});
// Graceful shutdown handling
process.on('SIGTERM', () => {
log('info', 'π SIGTERM received, shutting down gracefully...');
server.close(() => {
log('info', 'β
Server closed');
process.exit(0);
});
});
process.on('SIGINT', () => {
log('info', 'π SIGINT received, shutting down gracefully...');
server.close(() => {
log('info', 'β
Server closed');
process.exit(0);
});
});
} catch (error) {
log('error', 'β Failed to start server:', error);
process.exit(1);
}
};
// Handle uncaught exceptions
process.on('uncaughtException', (error: Error) => {
log('error', 'π₯ Uncaught Exception:', error);
process.exit(1);
});
// Handle unhandled promise rejections
process.on('unhandledRejection', (reason: any, promise: Promise<any>) => {
log('error', 'π₯ Unhandled Rejection at:', { reason, promise });
process.exit(1);
});
log('info', 'π Initializing server startup...');
// Start the application
startServer();