Skip to content

Commit 8a717ad

Browse files
fix backend
1 parent 904bbc0 commit 8a717ad

File tree

1 file changed

+88
-16
lines changed

1 file changed

+88
-16
lines changed

backend/index.js

Lines changed: 88 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -4,49 +4,87 @@ const fs = require('fs');
44
const express = require('express');
55
const cors = require('cors');
66
const sqlite3 = require('sqlite3').verbose();
7+
78
const { initDbIfNeeded } = require('./services/dbInit');
9+
const { initCatalogSchema } = require('./services/careerCatalog');
810

911
const authRoutes = require('./routes/auth');
1012
const profileRoutes = require('./routes/profile');
1113
const chatRoutes = require('./routes/chat');
1214
const adminRoutes = require('./routes/admin');
1315
const analyticsRoutes = require('./routes/analytics');
1416
const exploreRoutes = require('./routes/explore');
15-
const { initCatalogSchema } = require('./services/careerCatalog');
1617

1718
const app = express();
18-
app.use(cors());
19+
20+
/* =========================
21+
ENV + BASIC CONFIG
22+
========================= */
23+
24+
const PORT = process.env.PORT || 3001;
25+
const FRONTEND_URL = process.env.FRONTEND_URL || "*";
26+
27+
/* =========================
28+
MIDDLEWARE
29+
========================= */
30+
31+
// CORS fix cho production
32+
app.use(cors({
33+
origin: FRONTEND_URL,
34+
credentials: true
35+
}));
36+
1937
app.use(express.json());
2038

21-
const DB_PATH = process.env.DB_PATH || path.join(__dirname, 'database', 'career_advisor.db');
22-
function startServer() {
23-
const PORT = process.env.PORT || 3001;
24-
app.listen(PORT, () => {
25-
console.log(`API running on http://localhost:${PORT}`);
26-
});
39+
/* =========================
40+
DATABASE SETUP
41+
========================= */
42+
43+
// Đảm bảo thư mục database tồn tại
44+
const dbFolder = path.join(__dirname, 'database');
45+
if (!fs.existsSync(dbFolder)) {
46+
fs.mkdirSync(dbFolder, { recursive: true });
47+
console.log("📁 Created database folder");
2748
}
2849

50+
const DB_PATH = process.env.DB_PATH || path.join(dbFolder, 'career_advisor.db');
51+
52+
console.log("📦 Using DB at:", DB_PATH);
53+
2954
global.db = new sqlite3.Database(DB_PATH, async (err) => {
3055
if (err) {
31-
console.error('DB connect error:', err.message);
56+
console.error('DB connect error:', err.message);
3257
process.exit(1);
3358
}
34-
console.log('DB connected:', DB_PATH);
59+
60+
console.log('✅ DB connected');
61+
3562
try {
3663
const result = await initDbIfNeeded(global.db);
37-
if (result.seeded) {
38-
console.log('DB seeded with sample data');
64+
if (result?.seeded) {
65+
console.log('🌱 DB seeded with sample data');
3966
}
67+
4068
await initCatalogSchema();
69+
console.log('📚 Catalog schema ready');
70+
4171
} catch (e) {
42-
console.error('DB init failed:', e.message);
72+
console.error('DB init failed:', e.message);
4373
} finally {
4474
startServer();
4575
}
4676
});
4777

78+
/* =========================
79+
ROUTES
80+
========================= */
81+
4882
app.get('/health', (req, res) => {
49-
res.json({ ok: true, time: new Date().toISOString() });
83+
res.json({
84+
status: "ok",
85+
time: new Date().toISOString(),
86+
environment: process.env.NODE_ENV || "development"
87+
});
5088
});
5189

5290
app.use('/api/auth', authRoutes);
@@ -56,15 +94,49 @@ app.use('/api/admin', adminRoutes);
5694
app.use('/api/analytics', analyticsRoutes);
5795
app.use('/api/explore', exploreRoutes);
5896

97+
/* =========================
98+
FRONTEND SERVE (OPTIONAL)
99+
========================= */
100+
59101
const frontendDist = path.join(__dirname, '..', 'frontend', 'dist');
102+
60103
if (fs.existsSync(frontendDist)) {
104+
console.log("🌐 Serving frontend build");
105+
61106
app.use(express.static(frontendDist));
107+
62108
app.get('*', (req, res) => {
63109
if (req.path.startsWith('/api')) {
64-
return res.status(404).json({ success: false, error: 'Not found' });
110+
return res.status(404).json({ success: false, error: 'API not found' });
65111
}
66112
res.sendFile(path.join(frontendDist, 'index.html'));
67113
});
114+
68115
} else {
69-
console.warn('Frontend build not found. Run: npm --prefix frontend run build');
116+
console.log("ℹ️ Frontend build not found (normal if using GitHub Pages)");
70117
}
118+
119+
/* =========================
120+
START SERVER
121+
========================= */
122+
123+
function startServer() {
124+
app.listen(PORT, () => {
125+
console.log('🚀 ===============================');
126+
console.log(`🚀 Server running on port ${PORT}`);
127+
console.log(`🔗 Health check: /health`);
128+
console.log('🚀 ===============================');
129+
});
130+
}
131+
132+
/* =========================
133+
ERROR HANDLER
134+
========================= */
135+
136+
app.use((err, req, res, next) => {
137+
console.error("🔥 Server Error:", err);
138+
res.status(500).json({
139+
success: false,
140+
message: "Internal Server Error"
141+
});
142+
});

0 commit comments

Comments
 (0)