Background Story
Request validation is a must when developing an API. Express allows following options to achieve this.
Handling validation logic in each route handler (method-1)
router.post('/device/data', (req, res) => {
const {deviceID, serialNo} = req.body;
if(!deviceID || !serialNo) {
const err = new Error('invalid parameters')
res.status(400).json({err})
}
controller(req.body) // controller section
}
2. writing a separate middleware in each route handler (method-2)
router.post('/device/data', deviceDataValidationMiddleware, (req, res) => {
controller(req.body) // controller section
}
Method-1 is an ugly and painful way of achieving request validation. Method-2 is comparatively better, but still requires you to write a ton of middleware. Both methods demand a significant effort to unit test the route handler.
There has to be a better way of validating requests with less unit testing effort and of course by separating the concerns. xpress-req-validator
is the solution. It allows developers to define all their request validation specs in a single place, make route handling code snippets much cleaner and finally reducing the unit test effort
Last updated
Was this helpful?