feat: initialize microservice architecture with auth, api, realtime, copernicus, ml, and console modules

This commit is contained in:
Giuseppe Raffa
2026-03-28 15:29:34 +01:00
commit bcfce32adb
89 changed files with 12025 additions and 0 deletions

View File

@@ -0,0 +1,79 @@
const { Pool } = require('pg');
const config = {
user: process.env.PG_USER,
password: process.env.PG_PASSWORD,
host: process.env.PG_HOST,
port: process.env.PG_PORT,
max: 10,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 5000
}
const pools = {
users: new Pool({ ...config, database: process.env.DATA_DB }),
references: new Pool({ ...config, database: process.env.REFERENCES_DB }),
sensors: new Pool({ ...config, database: process.env.SENSOR_DB || 'users' })
}
Object.entries(pools).forEach(([name, pool]) => {
pool.on('error', (err) => {
console.error(`Error in ${name} pool`, err);
})
});
/**
*
* @param {'users' | 'references'} db - the name of the database
* @returns {Promise<import('pg').PoolClient>}
*/
async function getClient(db) {
const pool = pools[db];
if (!pool) throw new Error(`Database pool type ${db} does not exist`);
return await pool.connect();
}
/**
* Esegue una query sul database specificato
* @param {string} text - Query SQL
* @param {any[]} params - Parametri
* @param {'users' | 'references'} name - Quale DB usare
*/
async function query(text, params, name = 'users') {
const client = await getClient(name);
try {
return await client.query(text, params);
} catch (error) {
console.error(`[DB Query Error on ${name}]`, error.message);
throw error;
} finally {
client.release();
}
}
/**
* Inserisce una riga in una tabella
*/
async function append(table, data, type = 'users') {
const keys = Object.keys(data);
const values = Object.values(data);
const placeholders = keys.map((_, i) => `$${i + 1}`).join(', ');
const columns = keys.join(', ');
const sql = `INSERT INTO ${table} (${columns}) VALUES (${placeholders}) RETURNING *`;
return await query(sql, values, type);
}
/**
* Rimuove una riga
*/
async function remove(table, condition, params, type = 'users') {
const sql = `DELETE FROM ${table} WHERE ${condition}`;
return await query(sql, params, type);
}
module.exports = {
query,
append,
remove,
getClient,
pools
};