Performance: Repository pattern for data access
MEDIUM IMPACT
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 |