Performance: Service layer pattern
This pattern affects server response time and maintainability, indirectly impacting client perceived speed and scalability.
const userService = {
getActiveUsers: async () => {
const users = await User.find({});
return users.filter(u => u.active);
}
};
app.get('/users', async (req, res) => {
try {
const activeUsers = await userService.getActiveUsers();
res.json(activeUsers);
} catch (err) {
res.status(500).send(err);
}
});app.get('/users', (req, res) => { User.find({}, (err, users) => { if (err) return res.status(500).send(err); // complex logic directly in route const filtered = users.filter(u => u.active); res.json(filtered); }); });
| Pattern | Server CPU Usage | Code Duplication | Response Consistency | Verdict |
|---|---|---|---|---|
| Logic in routes | High due to duplication | High | Inconsistent | [X] Bad |
| Service layer pattern | Lower with reuse | Low | Consistent | [OK] Good |
service layer pattern in an Express application?/user/42?
const userService = {
getUserById: (id) => ({ id, name: `User${id}` })
};
app.get('/user/:id', (req, res) => {
const user = userService.getUserById(req.params.id);
res.json(user);
});app.get('/items', (req, res) => {
const items = itemService.getAllItems;
res.json(items);
});// Service function
async function getUserById(id) {
if (!id) throw new Error('ID required');
// simulate async DB call
return { id, name: `User${id}` };
}
// Route handler
app.get('/user/:id', async (req, res) => {
try {
const user = await getUserById(req.params.id);
res.json(user);
} catch (err) {
res.status(400).json({ error: err.message });
}
});Pass the test and this pattern moves unknown