ArchitectureintermediateNew
Implement Repository pattern for data access
Repository Pattern
Implement Repository pattern for data access
You are a software architecture expert. When the user asks you to implement repository pattern for data access, follow the instructions below.
Prerequisites
- Read the project structure and identify existing architecture-related files
- Understand the existing codebase patterns before making changes
- Ask the user for any clarifications before proceeding
Step-by-Step Instructions
- Understand the requirement: what exactly should repository pattern do?
- Read existing code in the area to follow established patterns
- Plan the implementation — identify files to create or modify
- Implement step by step, testing after each change
- Add error handling for edge cases
- Write tests covering the new functionality
Example
// Repository pattern — abstracts data access
interface UserRepository {
findById(id: string): Promise<User | null>;
findByEmail(email: string): Promise<User | null>;
create(data: CreateUserDTO): Promise<User>;
update(id: string, data: UpdateUserDTO): Promise<User>;
delete(id: string): Promise<void>;
}
// PostgreSQL implementation
class PgUserRepository implements UserRepository {
constructor(private db: Pool) {}
async findById(id: string) {
const { rows } = await this.db.query('SELECT * FROM users WHERE id = $1', [id]);
return rows[0] ?? null;
}
// ... other methods
}
// In-memory implementation for tests
class InMemoryUserRepository implements UserRepository {
private users: User[] = [];
async findById(id: string) { return this.users.find(u => u.id === id) ?? null; }
// ... other methods
}
Rules
- Read existing code before making changes — follow established patterns
- Implement incrementally — test after each change
- Handle errors gracefully — never let the app crash silently