import type { IUnitOfWork, TransactionContext } from "../types/index.js"; /** * Abstract Unit of Work * Provides transaction management across multiple repositories */ export abstract class UnitOfWork implements IUnitOfWork { protected currentContext: TransactionContext | null = null; protected repositoryCache: Map = new Map(); abstract begin(): Promise; /** * Execute work within a transaction * Auto-commits on success, rolls back on error */ async transaction( work: (ctx: TransactionContext) => Promise ): Promise { const ctx = await this.begin(); try { const result = await work(ctx); await ctx.commit(); return result; } catch (error) { if (ctx.isActive()) { await ctx.rollback(); } throw error; } finally { this.currentContext = null; this.repositoryCache.clear(); } } /** * Get repository instance (cached per transaction) */ getRepository(RepositoryClass: new (...args: any[]) => TRepo): TRepo { const key = RepositoryClass.name; if (this.repositoryCache.has(key)) { return this.repositoryCache.get(key); } const repo = this.createRepository(RepositoryClass); this.repositoryCache.set(key, repo); return repo; } /** * Create repository instance - implement in subclass */ protected abstract createRepository( RepositoryClass: new (...args: any[]) => TRepo ): TRepo; } /** * Base Transaction Context */ export abstract class BaseTransactionContext implements TransactionContext { protected _isActive = true; abstract commit(): Promise; abstract rollback(): Promise; isActive(): boolean { return this._isActive; } protected markInactive(): void { this._isActive = false; } }