66 lines
2.2 KiB
JavaScript
66 lines
2.2 KiB
JavaScript
const Pool = require('../../models/Pool');
|
|
|
|
class PoolRepository {
|
|
constructor(uow) {
|
|
this.uow = uow;
|
|
}
|
|
|
|
async create({ name, description = null, state = 'active', created_by }) {
|
|
const conn = this.uow.connection;
|
|
const [res] = await conn.execute(
|
|
`INSERT INTO pools (name, description, state, created_by, updated_by)
|
|
VALUES (?, ?, ?, ?, NULL)`,
|
|
[name, description, state, created_by]
|
|
);
|
|
return new Pool({ id: res.insertId, name, description, state, created_by, updated_by: null });
|
|
}
|
|
|
|
async findAll() {
|
|
const conn = this.uow.connection; // switched to connection
|
|
try {
|
|
console.debug('[PoolRepository.findAll] querying pools');
|
|
const [rows] = await conn.execute(
|
|
`SELECT id, name, description, state, created_at, updated_at
|
|
FROM pools
|
|
ORDER BY created_at DESC`
|
|
);
|
|
console.debug('[PoolRepository.findAll] rows fetched', { count: rows.length });
|
|
return rows.map(r => new Pool(r));
|
|
} catch (err) {
|
|
console.error('[PoolRepository.findAll] query failed', err);
|
|
// Surface a consistent error up the stack
|
|
const e = new Error('Failed to fetch pools');
|
|
e.status = 500;
|
|
e.cause = err;
|
|
throw e;
|
|
}
|
|
}
|
|
|
|
// NEW: update state with enforced transitions (active <-> inactive -> archived also supported)
|
|
async updateState(id, nextState, updated_by) {
|
|
const conn = this.uow.connection;
|
|
const [rows] = await conn.execute(`SELECT id, state FROM pools WHERE id = ?`, [id]);
|
|
if (!rows || rows.length === 0) {
|
|
const err = new Error('Pool not found');
|
|
err.status = 404;
|
|
throw err;
|
|
}
|
|
const current = rows[0].state;
|
|
const allowed = ['active', 'inactive', 'archived'];
|
|
if (!allowed.includes(current) || !allowed.includes(nextState)) {
|
|
const err = new Error('Invalid state transition');
|
|
err.status = 400;
|
|
throw err;
|
|
}
|
|
if (current === nextState) {
|
|
return new Pool({ id, state: current, updated_by }); // no-op
|
|
}
|
|
await conn.execute(
|
|
`UPDATE pools SET state = ?, updated_by = ?, updated_at = NOW() WHERE id = ?`,
|
|
[nextState, updated_by, id]
|
|
);
|
|
return new Pool({ id, state: nextState, updated_by });
|
|
}
|
|
}
|
|
|
|
module.exports = PoolRepository; |