feat: implement sensor connection and health check endpoints
This commit is contained in:
57
realtime/src/store/db.js
Normal file
57
realtime/src/store/db.js
Normal file
@@ -0,0 +1,57 @@
|
||||
const { Pool } = require('pg');
|
||||
const { get } = require('../../../api/src/routes/params.sensor');
|
||||
|
||||
const pool = new Pool({
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASSWORD,
|
||||
host: process.env.DB_HOST,
|
||||
port: process.env.DB_PORT,
|
||||
max: 10,
|
||||
idleTimeoutMillis: 30000,
|
||||
connectionTimeoutMillis: 5000,
|
||||
})
|
||||
|
||||
const dbs = {
|
||||
data: { name: process.env.DATA_DB },
|
||||
sensors: { name: process.env.SENSOR_DB }
|
||||
}
|
||||
|
||||
function getPool(db) {
|
||||
const dbConfig = dbs[db];
|
||||
if (!dbConfig) throw new Error(`Database ${db} not configured`);
|
||||
return new Pool({ ...pool.options, database: dbConfig.name });
|
||||
}
|
||||
|
||||
async function checkConnection(db) {
|
||||
try {
|
||||
await getPool(db).query('SELECT NOW()');
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error(`Error connecting to ${db} database`, err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function query(db, text, params) {
|
||||
const pool = getPool(db);
|
||||
return pool.query(text, params);
|
||||
}
|
||||
|
||||
async function init() {
|
||||
try {
|
||||
await query('sensors', `
|
||||
CREATE TABLE IF NOT EXISTS sensors (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(255) UNIQUE NOT NULL,
|
||||
code_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ DEFAULT NOW()
|
||||
);
|
||||
`);
|
||||
} catch (err) {
|
||||
console.error('Error creating sensors table', err);
|
||||
}
|
||||
}
|
||||
|
||||
init();
|
||||
|
||||
module.exports = { checkConnection, query };
|
||||
Reference in New Issue
Block a user