-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.js
More file actions
126 lines (114 loc) · 4.65 KB
/
db.js
File metadata and controls
126 lines (114 loc) · 4.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
// ============================================================================
// RENFE HISTORY CLIENT
//
// El servidor (Railway) recoge datos de la API de Renfe cada 30 minutos
// y los almacena en PostgreSQL.
//
// Este módulo simplemente consulta los endpoints del servidor para obtener
// estadísticas de probabilidad de retraso.
//
// Si el servidor no está disponible (desarrollo local sin backend),
// todas las funciones devuelven null y el modal muestra un mensaje informativo.
// ============================================================================
// URL del servidor Railway.
// - Vacío (''): la app se sirve desde Railway (mismo origen, sin CORS)
// - URL completa: la app se sirve desde otro host (ej. GitHub Pages)
// Cámbialo a tu URL de Railway: 'https://tu-app.up.railway.app'
const RAILWAY_URL = typeof window !== 'undefined' && window.RAILWAY_URL
? window.RAILWAY_URL
: '';
const API_BASE = RAILWAY_URL;
let backendOnline = false;
// ── Inicialización ──────────────────────────────────────────────────────────
async function initHistoryDB() {
try {
const res = await fetch(`${API_BASE}/api/info`, { signal: AbortSignal.timeout(3000) });
if (res.ok) {
const data = await res.json();
backendOnline = true;
const lastRun = data.collector?.lastSuccess
? new Date(data.collector.lastSuccess).toLocaleTimeString('es-ES')
: 'nunca';
console.log(`✅ Backend online — ${data.total} registros históricos · última recogida: ${lastRun}`);
}
} catch {
backendOnline = false;
console.log('ℹ️ Backend no disponible (modo local sin servidor)');
}
}
// ── Consultas ───────────────────────────────────────────────────────────────
async function getTrainStats(trainId) {
if (!backendOnline) return null;
try {
const res = await fetch(`${API_BASE}/api/stats/train/${encodeURIComponent(trainId)}`, {
signal: AbortSignal.timeout(5000)
});
if (res.ok) return await res.json();
if (res.status === 404) return null;
throw new Error(`HTTP ${res.status}`);
} catch (err) {
console.warn('getTrainStats error:', err.message);
return null;
}
}
async function getCorridorStats(corridor) {
if (!backendOnline) return null;
try {
const res = await fetch(`${API_BASE}/api/stats/corridor?c=${encodeURIComponent(corridor)}`, {
signal: AbortSignal.timeout(5000)
});
if (res.ok) return await res.json();
if (res.status === 404) return null;
throw new Error(`HTTP ${res.status}`);
} catch (err) {
console.warn('getCorridorStats error:', err.message);
return null;
}
}
async function getDBStats() {
if (!backendOnline) return { total: 0 };
try {
const res = await fetch(`${API_BASE}/api/info`, { signal: AbortSignal.timeout(3000) });
if (res.ok) return await res.json();
} catch { /* silencioso */ }
return { total: 0 };
}
async function getAllCorridorStats() {
if (!backendOnline) return null;
try {
const res = await fetch(`${API_BASE}/api/stats/corridors`, { signal: AbortSignal.timeout(8000) });
if (res.ok) return await res.json();
throw new Error(`HTTP ${res.status}`);
} catch (err) {
console.warn('getAllCorridorStats error:', err.message);
return null;
}
}
async function getHistoricalSummary() {
if (!backendOnline) return null;
try {
const res = await fetch(`${API_BASE}/api/stats/summary`, { signal: AbortSignal.timeout(5000) });
if (res.ok) return await res.json();
throw new Error(`HTTP ${res.status}`);
} catch (err) {
console.warn('getHistoricalSummary error:', err.message);
return null;
}
}
async function getDailyStats(date) {
if (!backendOnline) return null;
try {
const res = await fetch(`${API_BASE}/api/stats/daily/${date}`, {
signal: AbortSignal.timeout(5000)
});
if (res.ok) return await res.json();
throw new Error(`HTTP ${res.status}`);
} catch (err) {
console.warn('getDailyStats error:', err.message);
return null;
}
}
// Estas funciones ya no hacen nada — el servidor recoge los datos por su cuenta.
// Se mantienen para no romper las llamadas en app.js.
function updateTripCache() {}
async function flushTripCacheToDB() {}