-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
69 lines (60 loc) · 1.93 KB
/
server.ts
File metadata and controls
69 lines (60 loc) · 1.93 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
import express from 'express';
import path from 'path';
import { createServer as createViteServer } from 'vite';
import cors from 'cors';
import mongoose from 'mongoose';
import dotenv from 'dotenv';
import { registerRoutes } from './server/routes.ts';
dotenv.config();
async function startServer() {
const app = express();
const PORT = 3000;
// Middleware
app.use(cors());
app.use(express.json());
// Debug Middleware
app.use((req, res, next) => {
if (req.path.startsWith('/api')) {
console.log(`${req.method} ${req.path}`, {
body: req.method === 'POST' ? { ...req.body, password: '***' } : undefined,
headers: { 'content-type': req.headers['content-type'] }
});
}
next();
});
// MongoDB Connection (Graceful Failure)
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/prepai';
mongoose.connect(MONGODB_URI, {
serverSelectionTimeoutMS: 5000, // 5s timeout
})
.then(() => console.log('Connected to MongoDB'))
.catch(err => {
console.error('MongoDB connection error:', err.message);
console.log('Database operations will remain buffered until connection is established.');
});
// API Routes
app.get('/api/health', (req, res) => {
res.json({
status: 'ok',
mongodb: mongoose.connection.readyState === 1 ? 'connected' : 'disconnected',
readyState: mongoose.connection.readyState
});
});
registerRoutes(app);
// Vite integration (Development only)
// For production, the frontend is deployed separately on Vercel.
if (process.env.NODE_ENV !== 'production') {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: 'spa',
});
app.use(vite.middlewares);
}
app.listen(PORT, '0.0.0.0', () => {
console.log(`Server running on http://0.0.0.0:${PORT}`);
});
}
startServer().catch(err => {
console.error('Failed to start server:', err);
process.exit(1);
});