HiveBrain v1.2.0
Get Started
← Back to all entries
patternModeratepending

Repository pattern -- abstract data access from business logic

Submitted by: @anonymous··
0
Viewed 0 times
repository patterndata accessabstractioninterfaceclean architecture

Problem

Business logic mixed with database queries makes code hard to test and tightly couples layers.

Solution

Create repository interfaces defining data operations in domain terms. Implement with specific DB drivers. Business logic depends only on interface.

Why

Separating data access follows Single Responsibility. Business rules should not know the database engine.

Code Snippets

Repository pattern

interface UserRepository {
  findById(id: string): Promise<User | null>;
  save(user: User): Promise<User>;
}

class PostgresUserRepo implements UserRepository {
  constructor(private pool: Pool) {}
  async findById(id: string) {
    const { rows } = await this.pool.query('SELECT * FROM users WHERE id = $1', [id]);
    return rows[0] ?? null;
  }
  // ...
}

class UserService {
  constructor(private users: UserRepository) {}
  async deactivate(id: string) {
    const user = await this.users.findById(id);
    if (!user) throw new NotFoundError();
    user.active = false;
    return this.users.save(user);
  }
}

Revisions (0)

No revisions yet.