require('dotenv').config(); const express = require('express'); const cors = require('cors'); const { Pool } = require('pg'); const app = express(); const port = process.env.PORT || 3000; app.use(cors()); app.use(express.json()); const pool = new Pool({ host: process.env.DB_HOST || 'db', port: process.env.DB_PORT || 5432, user: process.env.POSTGRES_USER, password: process.env.POSTGRES_PASSWORD, database: process.env.POSTGRES_DB, }); async function initDatabase() { await pool.query(` CREATE TABLE IF NOT EXISTS attendance ( id SERIAL PRIMARY KEY, student_name VARCHAR(80) NOT NULL, arrival_time TIME NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); `); } app.get('/api/health', (req, res) => { res.json({ status: 'ok', service: 'attendance-backend' }); }); app.get('/api/attendance', async (req, res) => { try { const result = await pool.query('SELECT * FROM attendance ORDER BY created_at DESC, id DESC'); res.json(result.rows); } catch (error) { console.error(error); res.status(500).json({ error: 'Failed to load attendance entries' }); } }); app.post('/api/attendance', async (req, res) => { try { const { student_name, arrival_time } = req.body; if (!student_name || !arrival_time) { return res.status(400).json({ error: 'student_name and arrival_time are required' }); } const result = await pool.query( 'INSERT INTO attendance (student_name, arrival_time) VALUES ($1, $2) RETURNING *', [student_name, arrival_time] ); res.status(201).json(result.rows[0]); } catch (error) { console.error(error); res.status(500).json({ error: 'Failed to create attendance entry' }); } }); app.delete('/api/attendance/:id', async (req, res) => { try { await pool.query('DELETE FROM attendance WHERE id = $1', [req.params.id]); res.json({ deleted: true }); } catch (error) { console.error(error); res.status(500).json({ error: 'Failed to delete attendance entry' }); } }); initDatabase() .then(() => app.listen(port, () => console.log(`Attendance API running on port ${port}`))) .catch((error) => { console.error('Database initialization failed:', error); process.exit(1); });