Performance: Controller pattern for route handlers
This pattern affects server response time and how quickly the server can handle incoming requests, indirectly influencing perceived page load speed.
const userController = {
listActiveUsers: (req, res) => {
const users = database.getUsers();
const filtered = users.filter(u => u.active);
res.json(filtered);
}
};
app.get('/users', userController.listActiveUsers);app.get('/users', (req, res) => { // complex logic directly in route const users = database.getUsers(); const filtered = users.filter(u => u.active); res.json(filtered); });
| Pattern | Server CPU Usage | Code Maintainability | Response Time | Verdict |
|---|---|---|---|---|
| Inline route logic | High due to repeated code | Low, hard to maintain | Slower under load | [X] Bad |
| Controller pattern | Lower with reuse and caching | High, easier to maintain | Faster and scalable | [OK] Good |
controller pattern in Express route handlers?getUser in an Express route?getUser without parentheses passes the function itself. Using parentheses calls it immediately, which is incorrect here./hello?
const sayHello = (req, res) => {
res.send('Hello from controller!');
};
router.get('/hello', sayHello);sayHello function sends a plain text response 'Hello from controller!' when called.sayHello correctly as the handler for GET requests to '/hello'.const userController = {
getUser: (req, res) => {
res.json({ name: 'Alice' });
}
};
router.get('/user', userController.getUser());userController.getUser() immediately, which runs the function and passes its result, not the function itself.userController.getUser without parentheses.getUser, createUser, and deleteUser. Which approach best follows the controller pattern for clean code?userController.js file and importing them into the router file follows the pattern well.Pass the test and this pattern moves unknown