Repository Pattern (Architecture)
ELI5 — The Vibe Check
The repository pattern makes your database look like an in-memory collection. Instead of writing SQL, you call repository.findById(42) or repository.save(order). The actual database query is hidden behind the curtain. Your domain stays database-ignorant.
Real Talk
A design pattern that mediates between the domain model and data mapping layers, providing a collection-like interface for accessing domain objects. Repositories encapsulate the logic for querying and persisting aggregates, allowing the domain layer to remain infrastructure-agnostic. Often used with Unit of Work pattern.
Show Me The Code
interface OrderRepository {
findById(id: string): Promise<Order | null>;
save(order: Order): Promise<void>;
findByCustomer(customerId: string): Promise<Order[]>;
}
class PostgresOrderRepository implements OrderRepository {
async findById(id: string) {
const row = await this.db.query('SELECT * FROM orders WHERE id = $1', [id]);
return row ? this.toDomain(row) : null;
}
}
When You'll Hear This
"The repository returns domain objects, not database rows — it handles all the mapping." / "Use an in-memory repository for unit tests so you don't need a running database."
Related Terms
Data Access Layer (DAL)
The data access layer is the entire floor of your architecture that handles talking to databases.
Domain-Driven Design (DDD)
DDD says your code should speak the same language as the business.
Gateway Pattern
A gateway wraps access to an external system behind a nice, clean interface.
ORM (Object-Relational Mapper)
An ORM is like a translator between your code and your database. Instead of writing scary SQL, you just write normal code like `User.