← back to Watches
services/alert-evaluator.js
23 lines
import pool from '../database/connection.js';
export async function evaluateAlerts() {
const result = await pool.query(`
SELECT a.*, ap.avg_price as current_price FROM price_alerts a
JOIN aggregated_prices ap ON a.watch_id = ap.watch_id
WHERE a.is_active = true AND a.triggered_at IS NULL
`);
const triggered = [];
for (const alert of result.rows) {
const shouldTrigger = (alert.direction === 'below' && alert.current_price <= alert.target_price) ||
(alert.direction === 'above' && alert.current_price >= alert.target_price);
if (shouldTrigger) {
await pool.query(`UPDATE price_alerts SET triggered_at = NOW(), trigger_price = $1 WHERE id = $2`, [alert.current_price, alert.id]);
triggered.push(alert);
}
}
return triggered;
}
export default { evaluateAlerts };