Performance: Repository pattern
This pattern affects how data fetching and state management impact page load and interaction responsiveness.
class UserRepository { private userCache = null; constructor(private http: HttpClient) {} getUser() { if (this.userCache) return of(this.userCache); return this.http.get('/api/user').pipe(tap(data => this.userCache = data)); } } @Component({}) class ProfileComponent { constructor(private userRepo: UserRepository) {} ngOnInit() { this.userRepo.getUser().subscribe(); } } @Component({}) class DashboardComponent { constructor(private userRepo: UserRepository) {} ngOnInit() { this.userRepo.getUser().subscribe(); } }
class UserService { constructor(private http: HttpClient) {} getUser() { return this.http.get('/api/user'); } } @Component({}) class ProfileComponent { constructor(private userService: UserService) {} ngOnInit() { this.userService.getUser().subscribe(); } } @Component({}) class DashboardComponent { constructor(private userService: UserService) {} ngOnInit() { this.userService.getUser().subscribe(); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Multiple fetches in components | Low | Low | High due to blocking | [X] Bad |
| Repository with caching | Low | Low | Low, non-blocking | [OK] Good |
Repository pattern in NestJS?@InjectRepository() is used to inject repositories.@InjectRepository(User) which is the official and correct syntax.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();
}
}this.userRepo.find() doesfind() method of TypeORM repository returns all records of the entity as an array.findAll()find() returns a Promise resolving to an array of User entities, findAll() returns that array.@Injectable()
export class ProductService {
constructor(private productRepository: Repository<Product>) {}
}@InjectRepository(Entity) decorator to work properly.@InjectRepository(Product) before the repository parameter.findActiveUsers() in your UserRepository that returns only users with isActive = true. Which approach correctly applies the Repository pattern in NestJS?findActiveUsers().Pass the test and this pattern moves unknown