Performance: Request validation
Request validation affects server response time and throughput by adding processing before business logic runs.
import Joi from 'joi'; const schema = Joi.object({ name: Joi.string().required(), age: Joi.number().required() }); app.post('/api/data', (req, res) => { const { error } = schema.validate(req.body); if (error) { res.status(400).send(error.message); return; } processData(req.body); res.send('Success'); });
app.post('/api/data', (req, res) => { if (!req.body.name || typeof req.body.name !== 'string') { res.status(400).send('Invalid name'); return; } if (!req.body.age || typeof req.body.age !== 'number') { res.status(400).send('Invalid age'); return; } // more manual checks... processData(req.body); res.send('Success'); });
| Pattern | CPU Usage | Event Loop Blocking | Code Complexity | Verdict |
|---|---|---|---|---|
| Manual if-checks | High | High | High | [X] Bad |
| Validation library (e.g., Joi) | Medium | Low | Low | [OK] Good |
app.post('/signup', [
check('email').isEmail(),
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.send('Success');
}
]);app.post('/login', [
check('password').isLength({ min: 6 }),
(req, res) => {
const errors = validationResult;
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
res.send('Logged in');
}
]);Pass the test and this pattern moves unknown