Performance: Repository pattern for data access
This pattern affects how data fetching and manipulation impact server response time and resource usage.
class UserRepository { constructor(model) { this.model = model; this.cache = null; } async getAllUsers() { if (!this.cache) { this.cache = await this.model.find(); } return this.cache; } } const userRepo = new UserRepository(UserModel); app.get('/users', async (req, res) => { const users = await userRepo.getAllUsers(); res.json(users); });
app.get('/users', async (req, res) => { const users = await UserModel.find(); const usersAgain = await UserModel.find(); res.json(users); });
| Pattern | Database Queries | Server CPU Load | Response Time | Verdict |
|---|---|---|---|---|
| Direct DB calls in route handlers | Multiple redundant queries | Higher due to repeated calls | Slower due to query overhead | [X] Bad |
| Repository pattern with caching | Single query reused | Lower CPU load | Faster response | [OK] Good |
Repository pattern in an Express app?class keyword with methods inside without the function keyword.getAll() using ES6 syntax.console.log(users) output?class UserRepository {
constructor() {
this.users = [{id:1, name:'Anna'}, {id:2, name:'Bob'}];
}
getAll() {
return this.users;
}
}
const repo = new UserRepository();
const users = repo.getAll();
console.log(users);this.users to an array of two user objects.getAll() method returns this.users, so calling it returns the array.class ProductRepository {
constructor() {
this.products = [];
}
add(product) {
this.products.push(product);
}
getAll() {
return products;
}
}products but this variable is not defined in the method scope.this.products to access the class property.findByEmail(email) for users. Which approach correctly implements this in Express?extends keyword and super() if constructor is needed.BaseRepository and uses this.data to find user by email.Pass the test and this pattern moves unknown