Performance: Schema validation
Schema validation affects the server response time and user experience by adding processing before sending data back or accepting input.
Jump into concepts and practice - no test required
import Joi from 'joi'; const schema = Joi.object({ name: Joi.string().required(), age: Joi.number().required() }); app.post('/user', (req, res) => { const { error } = schema.validate(req.body); if (error) return res.status(400).send(error.message); res.send('User created'); });
app.post('/user', (req, res) => { const data = req.body; if (!data.name || typeof data.name !== 'string') { return res.status(400).send('Invalid name'); } if (data.age === undefined || typeof data.age !== 'number') { return res.status(400).send('Invalid age'); } // more manual checks... res.send('User created'); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual validation with many checks | 0 (server-side) | 0 | 0 | [X] Bad |
| Schema validation with Joi or similar | 0 (server-side) | 0 | 0 | [OK] Good |
username?username must be a string and required, so use Joi.string().required().schema.validate(data) return?const schema = Joi.object({ age: Joi.number().min(18).required() });
const data = { age: 16 };app.post('/user', (req, res) => {
const schema = Joi.object({ email: Joi.string().email().required() });
const result = schema.validate(req.body.email);
if (result.error) {
res.status(400).send('Invalid email');
} else {
res.send('User created');
}
});phone that must be a string of 10 digits if present, and a required name string. Which Joi schema correctly enforces this?