I am following this guide running-imperatively and trying to implement the sequential processing sample.
const validate = validations => {
return async (req, res, next) => {
for (let validation of validations) {
const result = await validation.run(req);
if (result.errors.length) break;
}
const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}
res.status(400).json({ errors: errors.array() });
};
};
The only significant eslint error I can't get around is no-await-in-loop Here is the current state of my code
One of the differences from the above sample is I'm not sending res
in this middleware; instead, it's passed on to next
const validate = (validations) => async (req, res, next) => {
const validationPromises = [];
// lodash function :)
_.forEach(validations, (validation) => {
const validationPromise = new Promise((resolve, reject) => {
validation.run(req).then((result) => {
if (result.errors.length) {
reject('Error');
} else {
resolve();
}
});
});
validationPromises.push(validationPromise);
});
Promise.all(validationPromises).then(next).catch(next);
};
The issue that I see is even though I'm reject
ing if the validation run has an error, all the validations are still executed.
I have ensured the reject
is correctly called, but all the Promiss are still executed. I'd expect if any Promise within Promise.all
was rejected, it would stop the execution of the rest of the Promises.
Here is how the validate middleware is called,
router.post(
'/submit',
validate([
body('challenge')
.notEmpty({ ignore_whitespace: true })
.withMessage('Invalid request. Please try login again'),
body('email').isEmail().withMessage('Please provide a valid email'),
body('comment')
.notEmpty({ ignore_whitespace: true })
.withMessage('Please provide a valid comment'),
body('tosChecked')
.isBoolean()
.withMessage('Please select Terms of service'),
]),
(req, res, next) => {
...
}
);
Thanks for any feedback.