Spaces:
Running
Running
| import express from 'express'; | |
| import cors from 'cors'; | |
| import morgan from 'morgan'; | |
| import dotenv from 'dotenv'; | |
| import path from 'path'; | |
| import { fileURLToPath } from 'url'; | |
| import projectRoutes from './routes/projectRoutes.js'; | |
| import messageRoutes from './routes/messageRoutes.js'; | |
| import { login } from './controllers/authController.js'; | |
| import { getDb } from './config/db.js'; | |
| // Load environment variables | |
| dotenv.config(); | |
| const __filename = fileURLToPath(import.meta.url); | |
| const __dirname = path.dirname(__filename); | |
| const app = express(); | |
| const PORT = process.env.PORT || 5000; | |
| // Middleware | |
| app.use(cors({ | |
| origin: '*', // Adjust this for production security as needed | |
| methods: ['GET', 'POST', 'PUT', 'DELETE'], | |
| allowedHeaders: ['Content-Type', 'Authorization'] | |
| })); | |
| app.use(express.json()); | |
| app.use(morgan('dev')); | |
| // Test route | |
| app.get('/api/health', (req, res) => { | |
| res.status(200).json({ status: 'UP', message: 'Lyvuha.com portfolio backend is active' }); | |
| }); | |
| // API Routes | |
| app.post('/api/auth/login', login); | |
| app.use('/api/projects', projectRoutes); | |
| app.use('/api/messages', messageRoutes); | |
| // Database initialization | |
| getDb() | |
| .then(() => { | |
| console.log('SQLite database initialized successfully.'); | |
| }) | |
| .catch((err) => { | |
| console.error('Failed to initialize SQLite database:', err); | |
| }); | |
| // Serve frontend — Docker puts dist at /app/frontend/dist, local dev at ../../frontend/dist | |
| const frontendDistPath = process.env.NODE_ENV === 'production' | |
| ? path.resolve(__dirname, '../frontend/dist') | |
| : path.resolve(__dirname, '../../frontend/dist'); | |
| app.use(express.static(frontendDistPath)); | |
| // Fallback all non-API routes to index.html (SPA routing) | |
| app.get('*', (req, res) => { | |
| if (req.originalUrl.startsWith('/api')) { | |
| return res.status(404).json({ success: false, message: 'API Route not found' }); | |
| } | |
| res.sendFile(path.join(frontendDistPath, 'index.html')); | |
| }); | |
| // Global Error Handler | |
| app.use((err, req, res, next) => { | |
| console.error('Unhandled error:', err); | |
| res.status(500).json({ | |
| success: false, | |
| message: 'An unexpected server error occurred' | |
| }); | |
| }); | |
| app.listen(PORT, () => { | |
| console.log(`Backend server running on http://localhost:${PORT} in ${process.env.NODE_ENV || 'development'} mode`); | |
| }); | |