/**
* Request validation middleware
* Uses Zod for schema validation
*/
import { logger } from "@config/logger";
import { ZodError } from "zod";
/**
* Middleware factory for request validation using Zod schemas.
* @category Middlewares
* @template TBody Request body shape.
* @template TQuery Query string shape.
* @template TParams Route params shape.
* @param {object} schema Schema map to validate against.
* @param {ZodSchema<TBody>} [schema.body] Optional body schema.
* @param {ZodSchema<TQuery>} [schema.query] Optional query schema.
* @param {ZodSchema<TParams>} [schema.params] Optional params schema.
* @returns {Function} Express middleware.
*/
export function validateRequest(schema) {
return (req, res, next) => {
try {
// Validate request body
if (schema.body) {
req.body = schema.body.parse(req.body);
}
// Validate query parameters
if (schema.query) {
const validatedQuery = schema.query.parse(req.query);
// Replace the query object with validated data
Object.assign(req.query, validatedQuery);
}
// Validate request parameters
if (schema.params) {
req.params = schema.params.parse(req.params);
}
next();
}
catch (error) {
if (error instanceof ZodError) {
logger.warn({
validationErrors: error.errors,
url: req.url,
method: req.method,
}, "Request validation failed");
res.status(400).json({
success: false,
error: {
message: "Validation failed",
details: error.errors,
},
});
return;
}
next(error);
}
};
}
Source