const express = require('express'); const cors = require('cors'); require('dotenv').config(); const { sequelize, cleanupCheckedItems } = require('./models'); const shoppingRoutes = require('./routes/shopping'); const app = express(); const PORT = process.env.PORT || 3001; // Middleware app.use(cors()); app.use(express.json()); app.use(express.urlencoded({ extended: true })); // Routes app.use('/api/shopping', shoppingRoutes); // Health check endpoint app.get('/api/health', (req, res) => { res.json({ status: 'OK', message: 'Shopping List Server is running', timestamp: new Date().toISOString() }); }); // Error handling middleware app.use((err, req, res, next) => { console.error(err.stack); res.status(500).json({ error: 'Something went wrong!' }); }); // 404 handler app.use('*name', (req, res) => { res.status(404).json({ error: 'Route not found' }); }); // Initialize database and start server const startServer = async () => { try { // Test database connection await sequelize.authenticate(); console.log('Database connection established successfully.'); // Sync database (create tables if they don't exist) await sequelize.sync(); console.log('Database synchronized successfully.'); // Run initial cleanup await cleanupCheckedItems(); // Start the server app.listen(PORT, () => { console.log(`Shopping List Server is running on port ${PORT}`); console.log(`Health check available at: http://localhost:${PORT}/api/health`); console.log(`Shopping API available at: http://localhost:${PORT}/api/shopping`); }); } catch (error) { console.error('Unable to start server:', error); process.exit(1); } }; // Handle graceful shutdown process.on('SIGINT', async () => { console.log('\nShutting down gracefully...'); await sequelize.close(); process.exit(0); }); process.on('SIGTERM', async () => { console.log('\nShutting down gracefully...'); await sequelize.close(); process.exit(0); }); startServer();