-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
109 lines (91 loc) · 4.92 KB
/
Copy pathserver.js
File metadata and controls
109 lines (91 loc) · 4.92 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
/**
* ============================================================
* Parent Teacher Communication Smart Dashboard - Server Entry
* ============================================================
* Express app with MongoDB, JWT auth, role-based routing,
* static frontend serving, and global error handling.
*/
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const morgan = require('morgan');
const path = require('path');
require('dotenv').config();
// ─── Import Routes ────────────────────────────────────────────────────────────
const authRoutes = require('./routes/auth');
const mentorRoutes = require('./routes/mentor');
const subjectRoutes = require('./routes/subject');
const parentRoutes = require('./routes/parent');
const chatRoutes = require('./routes/chat');
const app = express();
const PORT = process.env.PORT || 5000;
// ─── Middleware ────────────────────────────────────────────────────────────────
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// HTTP request logging (only in development)
if (process.env.NODE_ENV !== 'production') {
app.use(morgan('dev'));
}
// ─── Serve Static Frontend ─────────────────────────────────────────────────────
app.use(express.static(path.join(__dirname, 'frontend')));
// ─── API Routes ───────────────────────────────────────────────────────────────
app.use('/api', authRoutes);
app.use('/api/mentor', mentorRoutes);
app.use('/api/subject', subjectRoutes);
app.use('/api/parent', parentRoutes);
app.use('/api/chat', chatRoutes);
// ─── Health Check Endpoint ────────────────────────────────────────────────────
app.get('/api/health', (req, res) => {
res.json({ status: 'ok', message: 'Parent Teacher Dashboard API is running.' });
});
// ─── Frontend Catch-all (SPA fallback) ────────────────────────────────────────
// Redirect root to login page
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'frontend', 'login.html'));
});
// ─── 404 Handler ─────────────────────────────────────────────────────────────
app.use((req, res, next) => {
res.status(404).json({ message: `Route not found: ${req.method} ${req.originalUrl}` });
});
// ─── Global Error Handler ─────────────────────────────────────────────────────
// eslint-disable-next-line no-unused-vars
app.use((err, req, res, next) => {
console.error('❌ Global Error:', err.stack || err.message);
// Mongoose validation error
if (err.name === 'ValidationError') {
const messages = Object.values(err.errors).map((e) => e.message);
return res.status(400).json({ message: 'Validation Error', errors: messages });
}
// Mongoose cast error (invalid ObjectId)
if (err.name === 'CastError') {
return res.status(400).json({ message: 'Invalid ID format.' });
}
// Duplicate key error
if (err.code === 11000) {
const field = Object.keys(err.keyValue)[0];
return res.status(409).json({ message: `${field} already exists.` });
}
res.status(err.status || 500).json({
message: err.message || 'Internal server error.',
});
});
// ─── Connect to MongoDB and Start Server ──────────────────────────────────────
const startServer = async () => {
try {
await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log('✅ Connected to MongoDB');
app.listen(PORT, () => {
console.log(`🚀 Server running on http://localhost:${PORT}`);
console.log(`📚 Frontend: http://localhost:${PORT}/login.html`);
console.log(`🔑 API Docs: http://localhost:${PORT}/api/health`);
});
} catch (error) {
console.error('❌ MongoDB connection failed:', error.message);
process.exit(1);
}
};
startServer();