Performance: Request and response schemas
This concept affects the speed of processing incoming requests and sending responses, impacting server response time and perceived page load speed.
const Joi = require('joi'); const userSchema = Joi.object({ name: Joi.string().required(), age: Joi.number().min(0) }); app.post('/user', (req, res) => { const { error } = userSchema.validate(req.body); if (error) return res.status(400).send(error.details[0].message); // Process valid user res.send('User created'); });
app.post('/user', (req, res) => { // No validation const user = req.body; // Process user directly res.send('User created'); });
| Pattern | CPU Overhead | Error Prevention | Client Impact | Verdict |
|---|---|---|---|---|
| No schema validation | None | Low | High risk of client errors | [X] Bad |
| Full schema validation on request and response | Low (~1-3ms) | High | Improves client stability and LCP | [OK] Good |
const schema = Joi.object({ name: Joi.string().required() });
app.post('/data', (req, res, next) => {
const { error } = schema.validate(req.body);
if (error) return res.status(400).send(error.message);
res.send('Valid data');
});
What will the response be if the client sends {} as JSON body?app.post('/item', (req, res) => {
const { id, price } = req.body;
if (typeof id !== 'number' || typeof price !== 'number') {
res.status(400).send('Invalid data');
return;
}
res.send('Item accepted');
});
What is the main bug in this code?Pass the test and this pattern moves unknown