feat: update session handling and add session history endpoint
This commit is contained in:
@@ -2,7 +2,7 @@ const { Pool } = require('pg');
|
||||
|
||||
const baseConfig = {
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PSW,
|
||||
password: process.env.DB_PASSWORD,
|
||||
host: process.env.DB_HOST,
|
||||
port: process.env.DB_PORT,
|
||||
max: 10,
|
||||
@@ -11,14 +11,19 @@ const baseConfig = {
|
||||
};
|
||||
|
||||
const dbs = {
|
||||
data: { name: process.env.DATA_DB },
|
||||
sensors: { name: process.env.SENSORS_DB }
|
||||
data: { name: process.env.DATA_DB || 'data' },
|
||||
sensors: { name: process.env.SENSORS_DB || 'sensors' }
|
||||
}
|
||||
|
||||
const pools = {};
|
||||
|
||||
function getPool(db) {
|
||||
const dbConfig = dbs[db];
|
||||
if (!dbConfig) throw new Error(`Database ${db} not configured`);
|
||||
return new Pool({ ...baseConfig, database: dbConfig.name });
|
||||
if (!pools[db]) {
|
||||
pools[db] = new Pool({ ...baseConfig, database: dbConfig.name });
|
||||
}
|
||||
return pools[db];
|
||||
}
|
||||
|
||||
async function checkConnection(db) {
|
||||
@@ -26,8 +31,8 @@ async function checkConnection(db) {
|
||||
await getPool(db).query('SELECT NOW()');
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error(`Error connecting to ${db} database`, err);
|
||||
return false;
|
||||
console.error(`Error connecting to ${db} database`, err.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,6 +43,7 @@ async function query(db, text, params) {
|
||||
|
||||
async function init() {
|
||||
try {
|
||||
// Tabella sensori
|
||||
await query('sensors', `
|
||||
CREATE TABLE IF NOT EXISTS sensors (
|
||||
id SERIAL PRIMARY KEY,
|
||||
@@ -46,11 +52,28 @@ async function init() {
|
||||
created_at TIMESTAMPTZ DEFAULT NOW()
|
||||
);
|
||||
`);
|
||||
|
||||
// Tabella sessioni: mappa session_id (tag InfluxDB) a metadati custom
|
||||
await query('sensors', `
|
||||
CREATE TABLE IF NOT EXISTS sessiondataref (
|
||||
id SERIAL PRIMARY KEY,
|
||||
session_id VARCHAR(32) UNIQUE NOT NULL,
|
||||
sensor_name VARCHAR(255) NOT NULL,
|
||||
name VARCHAR(255),
|
||||
description TEXT,
|
||||
tags TEXT[] DEFAULT '{}',
|
||||
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||
disconnected_at TIMESTAMPTZ,
|
||||
updated_at TIMESTAMPTZ DEFAULT NOW()
|
||||
);
|
||||
`);
|
||||
|
||||
console.log('[DB] Tabelle verificate (sensors, sessiondataref)');
|
||||
} catch (err) {
|
||||
console.error('Error creating sensors table', err);
|
||||
console.error('[DB] Error creating tables:', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
init();
|
||||
|
||||
module.exports = { checkConnection, query };
|
||||
module.exports = { checkConnection, query };
|
||||
|
||||
Reference in New Issue
Block a user