Reputation: 3742
I want to create an Express REST API and want to validate the request params and the request body. If everything is fine I want to call the controller logic.
My validation middleware is
const { validationResult } = require('express-validator/check');
module.exports = (req, res, next) => {
const validationErrors = req.validationResult();
if (!validationErrors.isEmpty()) {
// send a 400
}
next();
}
and I use it within my routes before calling the controller. This is a snippet of my topics.js route file
const validation = require('../middleware/validation.js');
const { check } = require('express-validator/check');
router.get('/', topicsController.getAllTopics);
router.get('/:topicId', [
check('topicId').isUUID()
], validation, topicsController.getTopicById);
router.post('/', authenticationCheck, authorizationCheck, [
check('parentTopicId').isUUID() || check('parentTopicId').isNull(), // check if it's a UUID. If not, check if it's null
!check('name').isEmpty(), // is it not empty?
], validation, topicsController.createTopic);
router.put('/:topicId', authenticationCheck, authorizationCheck, [
check('topicId').isUUID(),
check('parentTopicId').isUUID() || check('parentTopicId').isNull(),
!check('name').isEmpty(),
], validation, topicsController.updateTopic);
router.delete('/:topicId', authenticationCheck, authorizationCheck, [
check('topicId').isUUID()
], validation, topicsController.deleteTopic);
I tried to get into it with the docs
https://express-validator.github.io/docs/#basic-guide
but when launching the API I get this error
Error: Route.post() requires a callback function but got a [object Boolean]
So it seems I am not able to pass in an array first, then the validation middleware and then the controller.
Is there a way to fix the route file? I don't want to handle the validation logic within my controller file. I think this should be done before.
Upvotes: 1
Views: 1329
Reputation: 14171
You need to use oneOf to check for conditional params.
In your routes you use check('parentTopicId').isUUID() || check('parentTopicId').isNull()
but that returns a boolean and express needs a middleware. oneOf
was build especially for this.
Also you should replace !check
with check('name').not().isEmpty()
.
Upvotes: 1