Reputation: 1428
I'm using checkSchema as middleware to validate some query input. It's working but it is not throwing errors.
Here's part of my code:
Router
import express from "express";
import * as controller from "../controllers/productsController";
import schema from "../validations/apiSchema";
const router = express.Router();
router
.route("/")
.get(schema, controller.getAllProducts)
.post(controller.createProduct);
export default router;
Controller
export function getAllProducts(req: express.Request, res: express.Response) {
productsModel
.find(req.query)
.then((products) => res.json(products))
.catch((err) => res.status(500).json(err));
}
Schema
const apiSchema = validator.checkSchema({
company: {
in: ["query"],
isInt: true,
exists: true,
// force an error
custom: {
options: (value) => {
console.log(value)
throw new Error("name is required");
},
}
}
});
The query parameter was a random string. It "works", console.log is called at every request, but it doesn't raise any errors.
Upvotes: 1
Views: 2290
Reputation: 1428
I took a look at documentation and I saw that:
app.post(
'/user',
body('username').isEmail(),
body('password').isLength({ min: 5 }),
(req, res) => {
// you must get the errors by yourself
// even using checkSchema
const errors = validationResult(req); // <------
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
User.create({
username: req.body.username,
password: req.body.password,
}).then(user => res.json(user));
},
);
**These comments above are not part of the documentation
checkSchemas doesn't throw an error on its own. You must handle this yourself in the next middleware. In that case, I'll just return the error at the end, but you can do whatever you want.
So, that's it. Is it not complex but it is something easy to forget. For now, I'm using this small line in the script, that is enough to fix the whole thing:
export function getAllProducts(req: express.Request, res: express.Response) {
// now it throws errors
validator.validationResult(req).throw();
productsModel
.find(req.query)
.then((products) => res.json(products.length))
.catch((err) => res.status(500).json(err));
}
Upvotes: 1