70 lines
2.6 KiB
JavaScript
70 lines
2.6 KiB
JavaScript
const UnitOfWork = require('../../database/UnitOfWork');
|
|
const PoolRepository = require('../../repositories/pool/poolRepository');
|
|
|
|
function isValidState(state) {
|
|
return state === undefined || state === null || state === 'active' || state === 'inactive' || state === 'archived';
|
|
}
|
|
|
|
async function createPool({ name, description = null, state = 'active', actorUserId }) {
|
|
if (!isValidState(state)) {
|
|
const err = new Error('Invalid state. Allowed: active, inactive, archived');
|
|
err.status = 400;
|
|
throw err;
|
|
}
|
|
const uow = new UnitOfWork();
|
|
try {
|
|
console.debug('[PoolService.createPool] start', { name, state });
|
|
await uow.start();
|
|
const repo = new PoolRepository(uow);
|
|
const pool = await repo.create({ name, description, state, created_by: actorUserId });
|
|
await uow.commit();
|
|
console.debug('[PoolService.createPool] success', { id: pool.id });
|
|
return pool;
|
|
} catch (err) {
|
|
console.error('[PoolService.createPool] error', err);
|
|
try { await uow.rollback(); } catch (_) { console.warn('[PoolService.createPool] rollback failed'); }
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
async function listPools() {
|
|
const uow = new UnitOfWork();
|
|
try {
|
|
console.debug('[PoolService.listPools] start');
|
|
// Ensure connection exists even for read-only
|
|
await uow.start();
|
|
const repo = new PoolRepository(uow);
|
|
const pools = await repo.findAll();
|
|
await uow.commit(); // harmless commit; ensures proper cleanup if UnitOfWork requires it
|
|
console.debug('[PoolService.listPools] success', { count: pools.length });
|
|
return pools;
|
|
} catch (err) {
|
|
console.error('[PoolService.listPools] error', err);
|
|
try { await uow.rollback(); } catch (_) { console.warn('[PoolService.listPools] rollback failed'); }
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
async function updatePoolState(id, nextState, actorUserId) {
|
|
if (!isValidState(nextState) || !['active', 'inactive', 'archived'].includes(nextState)) {
|
|
const err = new Error('Invalid state. Allowed: active, inactive, archived');
|
|
err.status = 400;
|
|
throw err;
|
|
}
|
|
const uow = new UnitOfWork();
|
|
try {
|
|
console.debug('[PoolService.updatePoolState] start', { id, nextState });
|
|
await uow.start();
|
|
const repo = new PoolRepository(uow);
|
|
const updated = await repo.updateState(id, nextState, actorUserId);
|
|
await uow.commit();
|
|
console.debug('[PoolService.updatePoolState] success', { id, state: nextState });
|
|
return updated;
|
|
} catch (err) {
|
|
console.error('[PoolService.updatePoolState] error', err);
|
|
try { await uow.rollback(); } catch (_) { console.warn('[PoolService.updatePoolState] rollback failed'); }
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
module.exports = { createPool, listPools, updatePoolState }; |