diff --git a/realtime/src/helper/authdb.js b/realtime/src/helper/authdb.js index 1bb8a11..b409993 100644 --- a/realtime/src/helper/authdb.js +++ b/realtime/src/helper/authdb.js @@ -19,6 +19,25 @@ async function checkDB() { } } +async function initDB() { + try { + await pool.query(` + CREATE TABLE IF NOT EXISTS sensors ( + id VARCHAR(10) PRIMARY KEY, + name VARCHAR(100) NOT NULL, + code_hash TEXT NOT NULL UNIQUE, + is_active BOOLEAN DEFAULT TRUE, + last_seen TIMESTAMP DEFAULT NOW(), + created_at TIMESTAMP DEFAULT NOW() + ); + CREATE INDEX IF NOT EXISTS idx_sensors_code_hash ON sensors(code_hash); + `); + console.log('[DB] Database schema initialized (sensors table ensured)'); + } catch (error) { + console.error('[DB] Schema initialization failed:', error); + } +} + /** * Restituisce i dati del sensore in base al token ricevuto. * Il token viene hashato prima della comparazione con il database. diff --git a/realtime/src/index.js b/realtime/src/index.js index f4afde7..fd8b443 100644 --- a/realtime/src/index.js +++ b/realtime/src/index.js @@ -76,10 +76,11 @@ app.get('/sessions/:sensorId/csv', async (req, res) => { } }); -// --- HTTP server + WebSocket per watchers live --- -const server = app.listen(process.env.PORT, '0.0.0.0', () => { - console.log(`Realtime on port ${process.env.PORT}`); +const PORT = process.env.PORT || 3000; +const server = app.listen(PORT, '0.0.0.0', async () => { + console.log(`Realtime on port ${PORT}`); + await require('./helper/authdb').initDB(); }); const wss = new WebSocket.Server({ server, path: '/live' });