37 lines
971 B
JavaScript
37 lines
971 B
JavaScript
function validateRequest(schema, target = 'body') {
|
|
return (req, res, next) => {
|
|
const data = req[target];
|
|
const { error, value } = schema.validate(data, {
|
|
abortEarly: false,
|
|
stripUnknown: true
|
|
});
|
|
|
|
if (error) {
|
|
const errorDetails = error.details.map(detail => ({
|
|
field: detail.path.join('.'),
|
|
message: detail.message,
|
|
value: detail.context.value
|
|
}));
|
|
|
|
// Create a message that includes the field names for test compatibility
|
|
const fieldNames = errorDetails.map(err => err.field).join(', ');
|
|
const message = `Validation error: ${fieldNames}`;
|
|
|
|
return res.status(400).json({
|
|
success: false,
|
|
message: message,
|
|
errors: errorDetails,
|
|
details: errorDetails // For backward compatibility
|
|
});
|
|
}
|
|
|
|
// Replace the target data with validated and sanitized data
|
|
req[target] = value;
|
|
next();
|
|
};
|
|
}
|
|
|
|
module.exports = {
|
|
validateRequest
|
|
};
|