Junior — Middle
Explain the concept of a repository in the context of ORM and its role in working with a database.
sobes.tech AI
Answer from AI
In the context of ORM, a repository is an abstraction layer that encapsulates data access logic and interaction with the database. It provides methods for creating, reading, updating, and deleting objects (CRUD), hiding the details of SQL queries.
Role of the repository:
- Simplifies data handling by providing a convenient interface.
- Allows changing the data storage implementation without altering business logic.
- Helps maintain a clean architecture and separation of concerns.
Example in TypeScript using TypeORM:
class UserRepository {
constructor(private ormRepository: Repository<User>) {}
async findById(id: number): Promise<User | null> {
return this.ormRepository.findOneBy({ id });
}
async save(user: User): Promise<User> {
return this.ormRepository.save(user);
}
// other methods...
}