---
name: unit-of-work
description: This skill should be used when the user asks about "unit of work pattern", "when to use unit of work", "transaction management", "commit changes", "atomic operations", or mentions needing to coordinate multiple repository operations in a single transaction.
version: 1.0.0
---

# Unit of Work Pattern

## What Is It
The Unit of Work pattern maintains a list of objects affected by a business transaction and coordinates the writing out of changes. It ensures that all changes to multiple objects are committed atomically or rolled back together.

## When to Use
- **Multiple repository updates** - Changes span several aggregates
- **Transaction boundaries** - Need atomic commits
- **Change tracking** - Track modified entities
- **Batch operations** - Optimize multiple saves
- **Audit trails** - Track what changed

## When NOT to Use
- **Single entity operations** - Direct repository call is simpler
- **No transactions needed** - No consistency requirements
- **Simple CRUD** - Repository pattern alone is sufficient
- **Read-only operations** - No changes to track

## How to Implement

### TypeScript Implementation

```typescript
class UnitOfWork {
  private added: Entity[] = [];
  private modified: Entity[] = [];
  private deleted: Entity[] = [];

  registerNew(entity: Entity): void {
    this.added.push(entity);
  }

  registerDirty(entity: Entity): void {
    if (!this.modified.includes(entity)) {
      this.modified.push(entity);
    }
  }

  registerDeleted(entity: Entity): void {
    this.deleted.push(entity);
  }

  async commit(): Promise<void> {
    // Atomically persist all changes
    await this.transaction.begin();
    try {
      for (const entity of this.added) await this.repo.insert(entity);
      for (const entity of this.modified) await this.repo.update(entity);
      for (const entity of this.deleted) await this.repo.delete(entity);
      await this.transaction.commit();
    } catch (error) {
      await this.transaction.rollback();
      throw error;
    }
  }
}
```

## Code Examples
- `examples/unit-of-work.ts` - Basic implementation
- `examples/unit-of-work-advanced.ts` - Real-world example with banking

## Related Patterns
- **Repository** - Unit of Work coordinates repositories
- **Identity Map** - Track loaded entities
- **Transaction Script** - Alternative to Unit of Work
