What if you could change your database without rewriting your entire app?
Why Repository pattern in NestJS? - Purpose & Use Cases
Imagine building a NestJS app where you write raw database queries everywhere in your code to fetch or save data.
Every time you want to change the database or fix a bug, you have to hunt through many files to update those queries.
Scattering database code everywhere makes your app hard to maintain and test.
It's easy to introduce bugs or inconsistencies because data access logic is duplicated and mixed with business logic.
The Repository pattern centralizes all data access in one place.
It acts like a middleman between your app and the database, so you can change how data is stored without touching the rest of your code.
const users = await connection.query('SELECT * FROM users WHERE active = true');const users = await userRepository.findActiveUsers();
This pattern makes your code cleaner, easier to test, and flexible to switch databases or data sources.
In a NestJS e-commerce app, the Repository pattern lets you swap from a SQL database to a NoSQL one without rewriting your order processing logic.
Manual database queries scattered in code are hard to maintain.
Repository pattern centralizes data access logic.
It improves code clarity, testing, and flexibility.
Practice
Repository pattern in NestJS?Solution
Step 1: Understand the role of Repository pattern
The Repository pattern is designed to isolate data access logic from the rest of the application.Step 2: Identify what Repository does in NestJS
In NestJS, repositories handle database operations, keeping business logic clean and testable.Final Answer:
To separate data access logic from business logic -> Option AQuick Check:
Repository pattern = separate data access [OK]
- Confusing repository with controller responsibilities
- Thinking repository manages UI or HTTP directly
- Mixing repository with configuration management
Solution
Step 1: Recall the correct decorator for repository injection
In NestJS with TypeORM,@InjectRepository()is used to inject repositories.Step 2: Match the syntax with the correct option
@InjectRepository(User) private userRepository: Repository<User>; uses@InjectRepository(User)which is the official and correct syntax.Final Answer:
@InjectRepository(User) private userRepository: Repository<User>; -> Option DQuick Check:
@InjectRepository = correct injection [OK]
- Using wrong decorator names like @InjectableRepository
- Confusing @Inject with @InjectRepository
- Omitting the entity inside @InjectRepository()
findAll() return?
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
@Injectable()
export class UserService {
constructor(@InjectRepository(User) private userRepo: Repository<User>) {}
async findAll() {
return await this.userRepo.find();
}
}Solution
Step 1: Understand what
Thethis.userRepo.find()doesfind()method of TypeORM repository returns all records of the entity as an array.Step 2: Analyze the return type of
SincefindAll()find()returns a Promise resolving to an array of User entities,findAll()returns that array.Final Answer:
An array of all User entities from the database -> Option CQuick Check:
Repository.find() returns array [OK]
- Thinking find() returns a single entity
- Assuming find() is not a valid method
- Confusing Promise with null return
@Injectable()
export class ProductService {
constructor(private productRepository: Repository<Product>) {}
}Solution
Step 1: Check how repositories are injected in NestJS
Repositories must be injected with@InjectRepository(Entity)decorator to work properly.Step 2: Identify missing decorator in the code
The code misses@InjectRepository(Product)before the repository parameter.Final Answer:
Missing @InjectRepository decorator for productRepository -> Option AQuick Check:
Repository injection needs @InjectRepository [OK]
- Forgetting @InjectRepository decorator
- Using wrong decorator names
- Assuming repositories inject automatically without decorators
findActiveUsers() in your UserRepository that returns only users with isActive = true. Which approach correctly applies the Repository pattern in NestJS?Solution
Step 1: Understand extending repository for custom methods
To add custom queries, extend the Repository class and add methods likefindActiveUsers().Step 2: Confirm proper injection of custom repository
Inject the custom repository in services to keep data access logic encapsulated.Final Answer:
Extend the Repository class and add findActiveUsers() method, then inject this custom repository -> Option BQuick Check:
Custom repo methods = extend Repository [OK]
- Putting query logic in service instead of repository
- Using global functions outside repository pattern
- Adding static methods to entity instead of repository
Ready to prove it?
Pass the test and this pattern moves unknown
