maggie-api
Version:
🧙♀️ A magical Express middleware to auto-generate CRUD APIs for Mongoose models with validation, unique keys, and middlewares.
24 lines (23 loc) • 819 B
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateBody = void 0;
const validateBody = (schema) => {
return (req, res, next) => {
const { error, value } = schema.validate(req.body, {
abortEarly: false, // collect all errors
stripUnknown: true, // remove unknown keys
convert: true, // apply defaults and type conversions
});
if (error) {
return res.status(400).json({
success: false,
statusCode: 400,
message: "Validation error",
error: error.details.map((d) => d.message).join(", "),
});
}
req.body = value; // assign validated + defaulted data
next();
};
};
exports.validateBody = validateBody;