150 lines
4.7 KiB
JavaScript
150 lines
4.7 KiB
JavaScript
import pg from 'pg';
|
|
|
|
const { Pool } = pg;
|
|
|
|
function mapStationRow(row) {
|
|
if (!row) return null;
|
|
return {
|
|
pin: row.pin,
|
|
name: row.name,
|
|
machineName: row.machine_name || null,
|
|
createdAt: row.created_at,
|
|
updatedAt: row.updated_at
|
|
};
|
|
}
|
|
|
|
export class DbService {
|
|
/**
|
|
* Serviço de persistência Postgres para usuários autenticados e estações pareadas.
|
|
*/
|
|
constructor({ connectionString = process.env.DATABASE_URL, pool = null } = {}) {
|
|
this.connectionString = connectionString || null;
|
|
this.pool = pool || (this.connectionString
|
|
? new Pool({
|
|
connectionString: this.connectionString,
|
|
max: 10,
|
|
idleTimeoutMillis: 30000
|
|
})
|
|
: null);
|
|
this._schemaReady = false;
|
|
}
|
|
|
|
isConfigured() {
|
|
return Boolean(this.pool);
|
|
}
|
|
|
|
async ensureSchema() {
|
|
if (!this.pool || this._schemaReady) return;
|
|
|
|
await this.pool.query(`
|
|
CREATE TABLE IF NOT EXISTS users (
|
|
id TEXT PRIMARY KEY,
|
|
email TEXT,
|
|
name TEXT,
|
|
picture TEXT,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
)
|
|
`);
|
|
|
|
await this.pool.query(`
|
|
CREATE TABLE IF NOT EXISTS user_stations (
|
|
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
pin TEXT NOT NULL,
|
|
name TEXT NOT NULL,
|
|
machine_name TEXT,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
PRIMARY KEY (user_id, pin)
|
|
)
|
|
`);
|
|
|
|
this._schemaReady = true;
|
|
}
|
|
|
|
async _requirePool() {
|
|
if (!this.pool) {
|
|
throw new Error('Banco de dados Postgres não configurado (DATABASE_URL ausente).');
|
|
}
|
|
await this.ensureSchema();
|
|
return this.pool;
|
|
}
|
|
|
|
async upsertUser({ id, email = null, name = null, picture = null }) {
|
|
if (!id) throw new Error('Identificador do usuário (id/sub) é obrigatório.');
|
|
const pool = await this._requirePool();
|
|
const res = await pool.query(
|
|
`INSERT INTO users (id, email, name, picture, created_at, updated_at)
|
|
VALUES ($1, $2, $3, $4, NOW(), NOW())
|
|
ON CONFLICT (id) DO UPDATE SET
|
|
email = COALESCE(EXCLUDED.email, users.email),
|
|
name = COALESCE(EXCLUDED.name, users.name),
|
|
picture = COALESCE(EXCLUDED.picture, users.picture),
|
|
updated_at = NOW()
|
|
RETURNING id, email, name, picture`,
|
|
[String(id), email, name, picture]
|
|
);
|
|
return res.rows[0];
|
|
}
|
|
|
|
async listStations(userId) {
|
|
const pool = await this._requirePool();
|
|
const res = await pool.query(
|
|
`SELECT pin, name, machine_name, created_at, updated_at
|
|
FROM user_stations
|
|
WHERE user_id = $1
|
|
ORDER BY updated_at DESC`,
|
|
[String(userId)]
|
|
);
|
|
return res.rows.map(mapStationRow);
|
|
}
|
|
|
|
async upsertStation(userId, { pin, name, machineName = null }) {
|
|
const pool = await this._requirePool();
|
|
const cleanPin = String(pin || '').trim();
|
|
const cleanName = String(name || '').trim() || `Estação ${cleanPin}`;
|
|
const res = await pool.query(
|
|
`INSERT INTO user_stations (user_id, pin, name, machine_name, created_at, updated_at)
|
|
VALUES ($1, $2, $3, $4, NOW(), NOW())
|
|
ON CONFLICT (user_id, pin) DO UPDATE SET
|
|
name = EXCLUDED.name,
|
|
machine_name = COALESCE(EXCLUDED.machine_name, user_stations.machine_name),
|
|
updated_at = NOW()
|
|
RETURNING pin, name, machine_name, created_at, updated_at`,
|
|
[String(userId), cleanPin, cleanName, machineName]
|
|
);
|
|
const stations = await this.listStations(userId);
|
|
return { station: mapStationRow(res.rows[0]), stations };
|
|
}
|
|
|
|
async renameStation(userId, pin, name) {
|
|
const pool = await this._requirePool();
|
|
const cleanPin = String(pin || '').trim();
|
|
const cleanName = String(name || '').trim();
|
|
if (!cleanName) throw new Error('Nome da estação é obrigatório.');
|
|
|
|
const res = await pool.query(
|
|
`UPDATE user_stations
|
|
SET name = $1, updated_at = NOW()
|
|
WHERE user_id = $2 AND pin = $3
|
|
RETURNING pin, name, machine_name, created_at, updated_at`,
|
|
[cleanName, String(userId), cleanPin]
|
|
);
|
|
if (res.rowCount === 0) return null;
|
|
const stations = await this.listStations(userId);
|
|
return { station: mapStationRow(res.rows[0]), stations };
|
|
}
|
|
|
|
async deleteStation(userId, pin) {
|
|
const pool = await this._requirePool();
|
|
const cleanPin = String(pin || '').trim();
|
|
const res = await pool.query(
|
|
`DELETE FROM user_stations
|
|
WHERE user_id = $1 AND pin = $2`,
|
|
[String(userId), cleanPin]
|
|
);
|
|
const stations = await this.listStations(userId);
|
|
return { deleted: res.rowCount > 0, stations };
|
|
}
|
|
}
|