---
name: repository
description: This skill should be used when the user asks about "repository pattern", "when to use repository", "data access abstraction", "decouple persistence", "dao vs repository", or mentions needing to abstract data access logic from business logic.
version: 1.0.0
---

# Repository Pattern

## What Is It
The Repository pattern mediates between the domain and data mapping layers, providing a collection-like interface for accessing domain objects. It abstracts away the details of data storage, allowing the domain to focus on business logic.

## When to Use
- **Domain-driven design** - Isolate domain from persistence
- **Testability** - Mock repositories for unit testing
- **Multiple data sources** - Swap databases easily
- **Caching** - Add caching transparently
- **Complex queries** - Centralize query logic

## When NOT to Use
- **Simple CRUD** - Direct ORM is simpler
- **Prototype** - Adds unnecessary abstraction
- **Single data source** - Limited benefit
- **Tight deadlines** - Overhead may not be worth it

## How to Implement

### Implementation Steps
1. Define repository interface in domain layer
2. Create concrete implementation in infrastructure layer
3. Use dependency injection to provide implementation
4. Repository methods should reflect domain concepts, not SQL

### TypeScript Implementation

```typescript
// Repository interface
interface UserRepository {
  findById(id: string): Promise<User | null>;
  findAll(): Promise<User[]>;
  save(user: User): Promise<void>;
  delete(id: string): Promise<void>;
  findByEmail(email: string): Promise<User | null>;
}

// Implementation
class InMemoryUserRepository implements UserRepository {
  private users: Map<string, User> = new Map();

  async findById(id: string): Promise<User | null> {
    return this.users.get(id) || null;
  }

  async save(user: User): Promise<void> {
    this.users.set(user.id, user);
  }
}
```

## Code Examples
See `examples/` directory for runnable TypeScript implementations:
- `examples/repository.ts` - Basic implementation with in-memory storage
- `examples/repository-advanced.ts` - Real-world example with caching

## Related Patterns
- **Unit of Work** - Often used together
- **Specification** - Complex query specifications
- **DAO** - Similar but lower-level abstraction
