← back to Watches
api/alerts.js
31 lines
import pool from '../database/connection.js';
export async function getAlerts(req, res) {
if (!req.user) return res.status(401).json({ error: 'Not authenticated' });
const result = await pool.query(`SELECT a.*, w.model as watch_name FROM price_alerts a JOIN watches w ON a.watch_id = w.id WHERE a.user_id = $1 ORDER BY a.created_at DESC`, [req.user.id]);
res.json({ success: true, alerts: result.rows });
}
export async function createAlert(req, res) {
if (!req.user) return res.status(401).json({ error: 'Not authenticated' });
const { watchId, targetPrice, direction } = req.body;
const result = await pool.query(`INSERT INTO price_alerts (user_id, watch_id, target_price, direction) VALUES ($1, $2, $3, $4) RETURNING *`, [req.user.id, watchId, targetPrice, direction]);
res.json({ success: true, alert: result.rows[0] });
}
export async function updateAlert(req, res) {
if (!req.user) return res.status(401).json({ error: 'Not authenticated' });
const { id } = req.params;
const { isActive } = req.body;
await pool.query(`UPDATE price_alerts SET is_active = $1 WHERE id = $2 AND user_id = $3`, [isActive, id, req.user.id]);
res.json({ success: true });
}
export async function deleteAlert(req, res) {
if (!req.user) return res.status(401).json({ error: 'Not authenticated' });
await pool.query(`DELETE FROM price_alerts WHERE id = $1 AND user_id = $2`, [req.params.id, req.user.id]);
res.json({ success: true });
}
export default { getAlerts, createAlert, updateAlert, deleteAlert };